how do I get angular2 dependency injection to work with value providers

十年热恋 提交于 2019-12-01 07:14:17

问题


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.

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

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 ]
})

and inject into a Component constructor

// 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?

Here's a plunkr: http://plnkr.co/edit/sQwxyDqLkMTgVUjJ1yYF?p=preview


回答1:


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
  ) {

and provide it like

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

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()



来源:https://stackoverflow.com/questions/39344266/how-do-i-get-angular2-dependency-injection-to-work-with-value-providers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!