[Fixed] Access root services in Angular lazy loaded module


I am playing with Angular lazy loaded modules and want to access a root service say AuthService in lazy loaded modules. I want to access the singleton instance present in the root injector in the lazy loaded modules.

I am following https://angular.io/guide/providers and there are two statements causing the confusion:

When you add a service provider to the root application injector, it’s available throughout the app.

When the Angular router lazy-loads a module, it creates a new injector. This injector is a child of the root application injector. Imagine a tree of injectors; there is a single root injector and then a child injector for each lazy loaded module. The router adds all of the providers from the root injector to the child injector. When the router creates a component within the lazy-loaded context, Angular prefers service instances created from these providers to the service instances of the application root injector.

The first statement clearly indicates that I can access a root service anywhere in the app. Whereas the second one is saying that the lazy loaded modules would get their own injector and potentially their own instances of the services?

So is this possible to get the singleton instance of the service in a lazy loaded module?


if you are looking for only one instance through out the app you can specify

   providedIn: 'root',

this behaviour can also be overridden by specifying at app module
src/app/app.module.ts (providers)

The @Injectable() decorator identifies a service class. The providedIn property configures a specific ModuleInjector, here root, which makes the service available in the root ModuleInjector.

Child ModuleInjectors are created when lazy loading other @NgModules.

Reference Link

Leave a Reply

(*) Required, Your email will not be published