这个例子的完整源代码:
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 参数: