Angular 注入器层次结构

1. Platform Injector

2. Application Injector


调用bootstrapModule()时建立的就是Application Injector。bootstrap

官方文档:If you only specify providers at the top level (typically the root AppModule), the tree of injectors appears to be flat. All requests bubble up to the root NgModule injector that you configured with the bootstrapModule method.

3. LazyModule Injector


当要显示lazy-loading的Component时,这个Component实例由LazyModule Injector来注入。app

若是同一个服务在多个注入器(Application Injector和LazyModule Injector)被provide,容易致使bug:
ide

在Module类上定义forRoot()静态方法能够避免在不一样的注入器注册同一个服务:
clipboard.pngui

4. View Injector

在已经提到的3种Injector之下,还有View Injector。

在View中的element(尤为是当这个element携带了Component时),有一个本身的Injector(也就是View Injector)。View Injector的层次结构与DOM的层次结构基本相同。View Injector层次结构的最顶端就是加载Entry Component(组件树的根节点)的那个Module的Injector(Application Injector或LazyModule Injector)。spa



在上图中,Application Module有一个Injector,AppComponent有一个Injector,<form>有一个Injector(这个Injector提供了NgForm Directive),<input>有一个Ijector(这个Injector提供了NgModel Directive)。
得益于这种层级关系,NgModel能够经过DI拿到NgForm的实例,实现组件间交流。3d

<parent-component>
    <content-child-component></content-child-component>
</parent-component>

即便父组件将Content Child投影(project)到<ng-content>中,Content Child也能够经过DI拿到父组件的实例,实现父组件与Content Child之间的交流。code

完整视频

https://youtu.be/EoSn8qASqQAcomponent

相关文章
相关标签/搜索