调用bootstrapModule()时建立的就是Application Injector。bootstrap
官方文档:If you only specify providers at the top level (typically the rootAppModule
), the tree of injectors appears to be flat. All requests bubble up to the rootNgModule
injector that you configured with thebootstrapModule
method.
当要显示lazy-loading的Component时,这个Component实例由LazyModule Injector来注入。app
若是同一个服务在多个注入器(Application Injector和LazyModule Injector)被provide,容易致使bug:ide
在Module类上定义forRoot()静态方法能够避免在不一样的注入器注册同一个服务:ui
在已经提到的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