我如何获得angular2依赖注入以与价值提供者一起工作 [英] how do I get angular2 dependency injection to work with value providers

查看:63
本文介绍了我如何获得angular2依赖注入以与价值提供者一起工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在关注Dependency Injection的docs文档,并尝试复制

I'm following the angular docs for Dependency Injection and tried to duplication the section on dependency injection tokens. But it's clear I still don't get it.

我正在尝试使用value providerconfig:any注入到我的项目中.

I'm trying to use a value provider to inject an config:any into my project.

在最简单的层次上,我只想provide一个const字符串

At the simplest level, I just want to provide a const string

// app-modules.ts
const CFG_STRING = "I was declared externally and injected in ngModule"    
@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App ],
  providers: [
    {provide: CFG_STRING, useValue: CFG_STRING}
  ],
  bootstrap: [ App ]
})

inject进入组件构造器

// app.ts
const LOCAL_STRING = "I was declared in the local module"
export class App {
  constructor(
    // @Optional() cfgString: CFG_STRING
  ) {
    this.name = 'Angular2'
    this.local = LOCAL_STRING

    /* provided/injected */
    // this.injectedStr = cfgString
  }
}

但是,当我这样做时,该应用程序无法正确运行.我在做什么错了?

But when I do so the app doesn't run correctly. What am I doing wrong?

这是一个笨拙的人: http://plnkr.co/edit/sQwxyDqLkMTgVUjJ1yYF?p=preview

推荐答案

如果您不使用类型作为提供程序的键,而是字符串或OpaqueToken,则需要将键传递给@Inject()

If you don't use a type as key for the provider but instead a string or OpaqueToken you need to pass the key to @Inject()

constructor(
    @Inject('CFG_STRING') /* @Optional()*/ cfgString: CFG_STRING
  ) {

并提供类似的内容

  providers: [
    {provide: 'CFG_STRING', useValue: CFG_STRING}
  ],

CFG_STRING不是类型,因此不能用作键.您可以使用一些字符串,也可以提及OpaqueToken.它可以是任何字符串,只需在provide@Inject()

CFG_STRING is not a type and can therefore not be used as key. Either you use some string or mentioned an OpaqueToken. It can be any string, it just needs to match between provide and @Inject()

这篇关于我如何获得angular2依赖注入以与价值提供者一起工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆