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.
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:
AppModule
ProviderX
AppComponent
ProviderX
SubpageModule
SubpageComponent
ProviderX
AppModule
ProviderX
AppComponent
ProviderX
SubpageModule
ProviderX
SubpageComponent
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.
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.