I have a main module in my library which I can call with forRoot
and pass some config data (like seen here Pass config data using forRoot)
export const MODULE_OPTIONS = new InjectionToken<ModuleOptions>('MODULE_OPTIONS');
@NgModule({
imports: [
MySubModule.forRoot(//needs access to options)
]
})
export class MyModule {
static forRoot(options: ModuleOptions = {}): ModuleWithProviders {
return {
ngModule: MyModule,
providers: [
{
provide: MODULE_OPTIONS,
useValue: options
}
]
}
}
}
My Submodule now also needs access to the options I provide from outside when importing my Main Module "MyModule" into an application/module.
How can I pass my ModuleOptions I provide in MyModule.forRoot
to MySubModule
?
I can't find any official way for this scenario, so I find a way but it is a workaround.
You can call the MySubModule.forRoot in the MyModule.forRoot function and assign the providers. (But also you have the import/export the submodule if you have components/directives in the submodule.)
export const MODULE_OPTIONS = new InjectionToken<ModuleOptions>('MODULE_OPTIONS');
@NgModule({
//You don't have to import/export if MySubmodule doesn't have any component/directive declaration.
imports: [MySubModule],
exports:[MySubModule]
})
export class MyModule {
static forRoot(options: ModuleOptions = {}): ModuleWithProviders {
//Now we are able to provide services/values that uses options in the MySubmodule.
const moduleProviders= MySubmodule.forRoot(options).providers;
moduleProviders.push({provide: MODULE_OPTIONS,useValue: options});
return {ngModule: MyModule,providers: moduleProviders};
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With