KiraAG
KiraAG

Reputation: 783

Injection token not getting provided in feature modules

I had created Injection token for my rest endpoints config and I am providing multiple values for it at runtime. If the token is provided in appmodule and used in the global services its working, but If i tried to provide another data in a feature module and inject it in feature effects file, I am getting staticinjectorerror, no provider available. here is the codeInjection-token code

Upvotes: 2

Views: 2543

Answers (1)

Max Mumford
Max Mumford

Reputation: 2642

Tokens provided by lazy loaded modules are not accessible in the global scope; that is to say they are only available within the same module in which they are provided.

To get around this, you can implement static forRoot(): ModuleWithProviders in your feature module and import this in your root module. This basically lets your feature module provide some tokens in the root, to be available globally, with the rest of the module being lazily loaded.

Here's an example of a lazy loaded feature module that provides an InjectionToken to the global scope:

@NgModule({
  ...
})
export class LazyLoadedFeatureModule {

  /**
   * Provide tokens to the global scope
   */
  static forRoot(): ModuleWithProviders {
    return {
      ngModule: LazyLoadedFeatureModule,
      providers: [
        { provide: MY_INJECTION_TOKEN, useValue: MyInjectionValue, multi: true },
      ]
    }
  }

}

And here it is imported in the root module:

@NgModule({
  ...
  imports: [
    LazyLoadedFeatureModule.forRoot(),
  ],
  ...
})
export class AppModule { }

Hope that helps.

Upvotes: 5

Related Questions