Reasoning behind Lazy loaded Module having their own injector

Multi tool use
Reasoning behind Lazy loaded Module having their own injector
I often struggle about lazy loading and services, that have their own instance. Sometimes All Components in the lazy loaded module share a service, sometimes they don't. It get's even worse, if you have subroutes which also lazy load additional modules.
Why do lazy loaded modules get their own injector anyway, and don't just retrieve the root injector?
For me, it just creates problems and doesn't have any benefits, but there must be reason it was designed like that.
I hope I can design my software architecture better, if I know more about the concepts and reasoning behind this...
Edit:Thank you for your anwers. I'll try to clarify my question:
If you configure the router to not load a component, but instead to load a module via lazy load, the lazy loaded module get's a new Injector for all the dependency injection.
That leads to the following effects:
- If a component depends on an injectable (e.g. a Service) that is not provided from the module, the injectable from the root injector will be injected
- if a component depends on an injectable that is provided inside of the same module, a new instance is created (e.g. a seperate Service instance)
So if you have a FooService and a routing tree like this:
root (RootInjector)
- LazyModule1 (Injector1)
-- LazyComponent1
- LazyModule2 (Injector2)
-- LazyComponent2
The FooService for LazyComponent 1 is different from FooService of LazyComponent2.
However, if you just eagerload your components, it'll look like this:
root (rootInjector)
- Module1
-- Component1
- Module2
-- Component2
All Modules and components share the same Service.
What I don't understand is, why the lady loaded Module get's a new injector anyway. It doesn't really make sense to me, but has a lot of pitfalls.
Also see: https://angular.io/guide/styleguide#shared-feature-module
@Injector()
can you please clarify which injector you are talking about?
– mast3rd3mon
20 mins ago
have you included the
CommonModule
in the root .module and in any lazy loaded moduels??– mast3rd3mon
31 secs ago
CommonModule
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
do you mean the
@Injector()
decorator?– mast3rd3mon
1 hour ago