Angular 2 injector hierarchy and NgModule

前端 未结 2 1420
刺人心
刺人心 2021-01-18 12:15

I wonder how NgModule actually affects Angular 2 injector hierarchy.

What does the hierarchy look like in an app with nested modules? Does it create a n

2条回答
  •  -上瘾入骨i
    2021-01-18 13:05

    According to the Modules documentation: https://angular.io/docs/ts/latest/guide/ngmodule.html

    Angular registers these providers with the root injector of the module's execution context. That's the application's root injector for all modules loaded when the application starts.

    Angular can inject one of these provider services into any component in the application. If this module provides the HeroService, or any module loaded at launch provides the HeroService, Angular can inject the same HeroService intance into any app component.

    A lazy loaded module has its own sub-root injector which typically is a direct child of the application root injector.

    Lazy loaded services are scoped to the lazy module's injector. If a lazy loaded module also provides the HeroService, any component created within that module's context (e.g., 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.

    So, you have one injector that is shared between all the modules. However, lazy-loaded components will have a child injector

提交回复
热议问题