I have two modules AppModule and lazyLoadModule. where I am lazy loading lazyLoadModule from Appmodule. I want to share my providers with lazy loaded module refer . I have created a SharedProviderModule as follows and imported in AppModule using SharedProviderModule.forRoot():
import { NgModule, APP_INITIALIZER, ModuleWithProviders } from '@angular/core';
import { CounterService } from './counter.service';
@NgModule({
})
export class SharedProviderModule {
static forRoot(): ModuleWithProviders {
return {
ngModule: SharedProviderModule ,
providers: [ CounterService
{
provide: APP_INITIALIZER,
useFactory: appConfigFactory,
deps: [CounterService],
multi: true
},
]
}
}
}
As per the reference blog providers should have single instance for both modules, but right now for lazy loaded module new instance of provider is getting initiated. I am overriding some value using factory provider in SharedProviderModule which are not reflected in lazy loaded module. Is it something I forgot to do?
Your lazy loaded module will automatically have access to all providers registered in the app. When your lazy loaded module imports a module with forRoot
it actually registers those providers AGAIN, causing your issue.
You should never have a shared module containing providers, unless you don't want them to be singletons. If both your AppModule
and lazy loaded module require a provider then register or import it in your AppModule
and it will be available everywhere.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.