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

I follow the angular docs for Injection Dependency Injection and tried to duplicate the injection tokens section . But it is clear that I still do not understand this.

I am trying to use value providerfor input config:anyin my project.

At the simplest level, I just want the providestring const

// 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 injectinto the 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 this, the application does not work correctly. What am I doing wrong?

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

+3
source share
1

, OpaqueToken @Inject()

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

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

CFG_STRING . - , OpaqueToken. , provide @Inject()

+1

Source: https://habr.com/ru/post/1017183/


All Articles