TypeScript 和 Angular 5 抽象类中的依赖注入

Mic*_*ski 5 inheritance dependency-injection typescript angular

我得到了BaseComponent注入了一些依赖项的 。第一个依赖EntityService是正确且必要的。

AnyOtherService仅用于抽象内部BaseComponent。相反,将其注入里面的ChildComponent,它不使用,我想只有内部注入它BaseComonent

为什么我必须将它ChildComponent推向BaseComponent?最好的解决方案是将其封装在BaseComponent.

基础.component.ts

export abstract class BaseComponent {
  constructor(
    protected entityService: EntityService,
    // protected anyOtherService: AnyOtherService // @todo add this
  ) {
  }
}
Run Code Online (Sandbox Code Playgroud)

子组件.ts

@Component()
export class ChildComponent extends BaseComponent {

  constructor(
    private firstService: FirstService,
    private secondService: SecondService,
    protected anyOtherService: AnyOtherService // @todo remove this
  ) {
    super(
      firstService,
      anyOtherService // @todo remove this
    ); 
  }
}
Run Code Online (Sandbox Code Playgroud)

Yer*_*kon 4

因此,您可以将Injector传递给基础组件构造函数(更新):

export abstract class BaseComponent {
  protected anyOtherService: AnyOtherService;

  constructor(
    inject: Injector
    protected entityService: EntityService,
    // protected anyOtherService: AnyOtherService // @todo add this
  ) { 
     this.anyOtherService= inject.get(AnyOtherService);
  }
}


@Component()
  export class ChildComponent extends BaseComponent {

  constructor(
    inject: Injector,
    private firstService: FirstService,
    private secondService: SecondService       
  ) {
    super(
     inject,
     firstService
    );       
  }
}
Run Code Online (Sandbox Code Playgroud)

这个想法是在子组件中注入Injector和一些提供程序,并将其传递给父基组件,而不传递所有基类依赖项。通过传递注入器,子类(组件)不需要注入父(基)类的所有依赖项并传递 throw super(dep1, dep2..., baseDep1... )。

您能否在回答中解释一下,为什么它必须像您所说的私有内部子项和受保护内部父项一样?

我认为注入器不应该是子类/基类的属性。如果是,则会像您在下面评论时抛出错误。错误是关于 基类类在其类中不能具有相同的属性。这就是为什么我们需要在构造函数中省略 private/protected 或任何对注入器访问修饰符,也因为构造函数中只需要注入器来手动注入我们在某些特定情况下需要的东西。