当前我正在通过构造函数进行注入,如下所示,是否有其他方法可以在需要时向组件注入服务,而不是在构造函数上注入
export class AppService {
private users: User[] = [];
constructor( private backend: BackendService, private logger: Logger) { }
}
答案 0 :(得分:3)
我们可以将angular的Injector注入为依赖项,并在需要时使用它来将我们的服务注入为依赖项,如下所示,
import { Injector } from '@angular/core';
export class AppService {
private users: User[] = [];
constructor( private injector: Injector, private logger: Logger) { }
someMethod() {
let backendService: BackEndService = this.injector.get(BackEndService);
....
}
}