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:

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值