如何在子类Angular中注入服务?

我在Angular中有一个自定义的具体类,它扩展了抽象类:

version: '3'
services:
  foobar:
    build:
      context: ./foobar
    ports:
      - 8001:80
    depends_on:
      - barfoo
  barfoo:
    build:
      context: ./barfoo
    ports:
      - 8002:8002
    command: 'some-service --port 8002'

我使用的具体课程是:

abstract class Tab<T> {
   constructor(protected parameters: T,protected _activeIndexTab?: number) {}
}

export class TabDictionary extends Tab<ITabDictioaryParameters> {
  constructor(parameters?: ITabDictioaryParameters) {

}

问题是要在类this.tabService.register(new TabDictionary()).build(); 中使用Route的DI,我需要将依赖项添加到父抽象类中,该类具有冗余的依赖项。

如何简化它?

如果我的问题不够清楚,请告诉我

我想让TabDictionary拥有所有必需的依赖项,这些依赖项应该在子类中可用

fancykee 回答:如何在子类Angular中注入服务?

使用一个类来存储注射器 此类将容纳模块的注射器。一旦组件或服务需要获得服务依赖项,它将设置一次并检索。

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

大家都在问