0

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?

Imran Latif
  • 985
  • 8
  • 21
  • 1
    Does this answer your question? [Service is not being singleton for angular2 router lazy loading with loadChildren](https://stackoverflow.com/questions/40981306/service-is-not-being-singleton-for-angular2-router-lazy-loading-with-loadchildre) – satyen Apr 19 '21 at 13:33

1 Answers1

1

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

imsheth
  • 31
  • 2
  • 18
  • 36
satyen
  • 109
  • 5
  • Does this solution still works, if we declare the service in the root module's provider list, instead of using this Injectable annoation. In other word, as long as we don't declare the service in the lazy module's provider list, and we declare the service in the root module's provider list or using Injector({providedIn:'root'}), it should achieve what the poster wants. Do correct me , if my understanding is wrong – Nick Wills Jul 18 '21 at 15:07