加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Angular 注入器层次结构

发布时间:2020-12-17 08:27:08 所属栏目:安全 来源:网络整理
导读: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 req

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:

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

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)。



在上图中,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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读