繁体   English   中英

使用TypeScript和Angular 5在抽象类中进行依赖注入

[英]Dependency injection in abstract class with TypeScript and Angular 5

我有BaseComponent ,它注入了一些依赖BaseComponent 第一个依赖EntityService是正确和必要的。

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

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

base.component.ts

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

child.component.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
    ); 
  }
}

所以你可以将Injector传递给基础组件构造函数( UPDATE ):

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
    );       
  }
}

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

你可以在你的答案中解释一下,为什么它必须像你曾经说过私人内部孩子并且在父母内部受到保护?

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

你可以尝试这样,使用注入器,从appmodule导出它并在你的基类中使用它

import {Injector} from '@angular/core';

//exporting injector 
export let AppInjector: Injector;

export class AppModule {
  constructor(private injector: Injector) {
    AppInjector = this.injector;
  }
}

然后是base.component.ts

export abstract class BaseComponent {
  private anyOtherService : AnyOtherService ;
  constructor(
    protected entityService: EntityService,
    // protected anyOtherService: AnyOtherService // @todo add this
  ) {
    this.anyOtherService = AppInjector.get(AnyOtherService );
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM