这个例子的完整源代码:
import { Component, OnInit, Injectable, Injector } from '@angular/core'; @Injectable() class UsefulService { constructor(){ console.log("Useful Service is created"); } } @Injectable() class NeedsService { constructor(public service: UsefulService) { console.log("NeedsService is created"); } } const injector = Injector.create({ providers: [{ provide: NeedsService, deps: [UsefulService] }, { provide: UsefulService, deps: [] }] }); console.log(' true or false?' , injector.get(NeedsService).service instanceof UsefulService); @Component({ selector: 'manual_di', template: '<p>Manual DI </p>' }) export class ManualDIComponent implements OnInit { constructor() { } ngOnInit(): void { } }
单步调试
Injector.create
由实现源代码可见,Angular NgModule providers 元数据支持 name 参数:
NeedsService 的依赖服务是 UsefulService,维护在 deps 数组里:
观察最后返回的 injector 实例里,到底包含了哪些数据:
injector records 属性包含了 Providers NeedsService 和 UsefulService 两条记录,但是 value 为空,因为是惰性加载。
直到应用代码显式调用 injector.get 获取 providers 实例时,hydration 才会发生: