Reputation: 41
I have the following scenario:
I'd like LazyModuleA and LazyModuleB to receive the same instance of RefreshService. Instead, when I add console log statements to the constructor I can see that there are 2 separate instances being constructed lazily, when the lazy modules load.
I was under the impression the following solution should work, but I am still seeing the duplicate instances:
Injectable({ providedIn: 'root'})
export class RefreshService
Refresh service in providers array returned from static forRoot method in SharedModule
export class SharedModule {
static forRoot(): ModuleWithProviders<SharedModule> {
return {
ngModule: SharedModule,
providers: [ RefreshService ]
};
}
Import from tgz package to LazyModuleA and LazyModuleB
import { RefreshService } from 'shared-module';
...
// inject in constructor
In the base app module, call the forRoot method in the import
import { SharedModule } from 'shared-module';
...
imports: [
...
SharedModule.forRoot()
]
Has anyone had any luck with this scenario?
Upvotes: 0
Views: 205
Reputation: 57731
It's due to the fact you are using a lazy loaded module that the services are getting their own instances created!. It is provided in the angular documentation itself!
limiting-provider-scope-by-lazy-loading-modules
Any component created within a lazy loaded module's context, such as by router navigation, gets its own local instance of child provided services, not the instance in the root application injector. Components in external modules continue to receive the instances created for the application root injector.
Though you can provide services by lazy loading modules, not all services can be lazy loaded. For instance, some modules only work in the root module, such as the Router. The Router works with the global location object in the browser.
Upvotes: 0