Angular 注入器层次结构

发布时间:2019-06-16 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了Angular 注入器层次结构脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

1. Platform Injector

2. Application Injector


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

官方文档: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来注入。

如果同一个服务在多个注入器(Application Injector和LazyModule Injector)被provide,容易导致bug:

Angular 注入器层次结构

在Module类上定义forRoot()静态方法可以避免在不同的注入器注册同一个服务:

Angular 注入器层次结构

4. View Injector

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

Angular 注入器层次结构


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

Angular 注入器层次结构


Angular 注入器层次结构


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

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

即使父组件将Content Child投影(project)到<ng-content>中,Content Child也可以通过DI拿到父组件的实例,实现父组件与Content Child之间的交流。

完整视频

https://youtu.be/EoSn8qASqQA

脚本宝典总结

以上是脚本宝典为你收集整理的Angular 注入器层次结构全部内容,希望文章能够帮你解决Angular 注入器层次结构所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。