简体   繁体   中英

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

@Injectable({
   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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM