使用一个类来存储注射器
此类将容纳模块的注射器。一旦组件或服务需要获得服务依赖项,它将设置一次并检索。
app-injector.service.ts
import { Injector } from '@angular/core';
export class AppInjector {
private static injector: Injector;
static setInjector(injector: Injector) {
AppInjector.injector = injector;
}
static getInjector(): Injector {
return AppInjector.injector;
}
}
模块自举后,将模块的注入器存储在AppInjector类中。
main.ts
platformBrowserDynamic().bootstrapModule(AppModule).then((moduleRef) => {
AppInjector.setInjector(moduleRef.injector);
});
使用此注入器类分配依赖项
现在,我们可以修改基本组件以删除所有构造函数参数。
base.component.ts
@Component({
template: ''
})
export class BaseComponent {
protected utilitiesService: UtilitiesService;
protected loggingService: LoggingService;
constructor() {
// Manually retrieve the dependencies from the injector
// so that constructor has no dependencies that must be passed in from child
const injector = AppInjector.getInjector();
this.utilitiesService = injector.get(UtilitiesService);
this.loggingService = injector.get(LoggingService);
this.logNavigation();
}
protected logError(errorMessage: string) { . . . }
private logNavigation() { . . . }
}
从基础组件继承子组件
现在,子组件只需要对自己的依赖项使用依赖项注入。
child.component.ts
@Component({ . . . })
export class ChildComponent extends BaseComponent {
constructor(private childDataService: ChildDataService) {
super();
}
}
参考:https://devblogs.microsoft.com/premier-developer/angular-how-to-simplify-components-with-typescript-inheritance/
本文链接:https://www.f2er.com/3166821.html