Search code examples
angularangular-providers

Does Angular component from lazy loaded module gets copy of the global service?


Angular docs I'm not sure if I understand

Angular providers documentation states:

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.

Any component created within a lazy loaded module’s context, such as by router navigation, gets the local instance of the service, not the instance in the root application injector. Components in external modules continue to receive the instance created for the application root.

Question

Does it mean that when I access any globally declared provider in a lazy loaded module, I access it's copy, which is separate from the instance created in the root injector?

Let's say I have 2 situations:

Situation A

  • root module AppModule
    • provides ProviderX
    • declares AppComponent
      • injects ProviderX
  • lazy loaded module SubpageModule
    • no providers
    • declares SubpageComponent
      • injects ProviderX

Situation B

  • root module AppModule
    • provides ProviderX
    • declares AppComponent
      • injects ProviderX
  • lazy loaded module SubpageModule
    • provides ProviderX
    • declares SubpageComponent
      • injects ProviderX

In situation A does the instance of ProviderX in SubpageComponent is the same instance as in AppComponent or a different one? I understand in situation B they're not.


Solution

  • Situation A

    AppComponent and SubpageComponent get the same instance injected

    Situation B

    AppComponent and SubpageComponent get different instances injected

    With your setup you get an injector hierarchy like

    - AppModule
     |- AppComponent
     |- SubPageModule
       |- SubpageComponent
    

    Angular searches from the location where it needs to inject a value the tree structure upwards until it finds the first matching provider. Then it injects the instance provided by the first found provider.