-1

In the Angular docs it is mentioned, that in Lazy loading modules, components get local instances of services not the root level instances. Other module's components are using a root-level instance. Does this mean it creates 2 instances when we are using Lazy loading?

Case is:

  1. We have Root Module AppModule, where we created a service(ServiceA) and injected at root level, but now we don't provide this service into the AppModule's providers[] like this only : imports: [ BrowserModule, RouterModule.forRoot(routes) ], providers: [],

  2. Now in my lazy loaded module, I have to use the same service(ServiceA) just by importing it into some component of the lazily-loaded module.

Question: Does this create a separate instance of service(ServiceA) in the lazy loaded modules? Answer: Ideally it should create only one instance,

But due to this line I am confuse

enter image description here

Please help me with this understanding.

General Grievance
  • 4,555
  • 31
  • 31
  • 45
Yogesh
  • 35
  • 1
  • 7

2 Answers2

2

It will create a separate instance.

You can test this by setting a property with a unique value on construction and logging it on init for each lazy loaded module. The value will not be the same.

See this answer for a possible solution: how to share same service instance between 2 lazy loaded modules - not at root

Lee
  • 703
  • 6
  • 20
1

based on your description,

  • you aren't explicitly defining the service in a module's provider array.
  • therefore, as long as your service has the @Injectable() ({ providedIn: 'Root' }) decorator, your root app and lazy loaded app would have the same service instance.

as defined in the documentation, if you started specifying providers for specific modules or components, that is how you could accomplish have multiple instances

Edward
  • 1,076
  • 1
  • 12
  • 24