1

I found some examples of module's forRoot() method like the one below:

export class CoreModule {
constructor(
@Optional()
@SkipSelf()
parentModule: CoreModule
) {
if (parentModule) {
  throw new Error(
    'CoreModule is already loaded. Import it in the AppModule only'
  );
 }
}
static forRoot(someParameters?:string[]): ModuleWithProviders {
  return {
  ngModule: CoreModule,
  providers: [AnProvider1, AnProvider2]
 };
}

But how can I to pass the parameter values to any of the module's declared providers ?

Cristiano
  • 1,414
  • 15
  • 22

1 Answers1

7

Use InjectionToken to register the parameters with the injector. Then use DI passing in the InjectionToken with the deps property as follows:

export const Params= new InjectionToken<string[]>('params');

...

static forRoot(someParameters?:string[]): ModuleWithProviders {
  return {
  ngModule: CoreModule,
  providers: [
            { provide: Params, useValue: someParameters },
            { provide: AnProvider1, useClass: AnProvider1, deps:[Params] },
            AnProvider2
  ]
};

In your component constructor, use the InjectionToken:

constructor(@Inject(Params) someParameters: string[])
Michael Kang
  • 52,003
  • 16
  • 103
  • 135