Используйте класс для хранения инжектора Этот класс будет содержать инжектор модуля. Он будет установлен один раз и извлечен всякий раз, когда компонент или служба должны получить зависимость от службы.
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/