簡體   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