簡體   English   中英

為其他服務注入服務

[英]Injecting service for another service

我幾乎沒有服務級別可以互相調用,即ComponentService使用DataService ,而DataService使用ErrorService

現在,組件服務之一需要指定DataService使用的ErrorService實例應為例如SpecialErrorService類型。 -並且它不直接使用ErrorServiceSpecialErrorService

實例化時,如何指示數據服務注入正確的ErrorService類型? (請注意,我只希望對特定的ComponentService采取這種行為,而不是一般情況)

@Injectable()
export class SpecialComponentService {
  constructor(private _dataService: DataService){}

  log() {
     //expecting this to log: I'm a special error service
     this._dataService.log();
  }
}

@Injectable()
export class RegularComponentService {
  constructor(private _dataService: DataService){}

  log() {
     //expecting this to log: I'm a regularerror service
     this._dataService.log();
  }
}

@Injectable()
export class DataService {
  constructor(private _errorService: ErrorService){}

  log() {
     this._errorService.log();
  }
}


@Injectable()
export class ErrorService {
  log(){
    console.log("I'm a regular error service");
  }
}

@Injectable()
export class SpecialErrorService extends ErrorService {
  log(){
    console.log("I'm a special error service");
  }
}

提供服務時,可以用特殊服務代替。 例如,如果您在組件中使用它,則可以這樣提供:

{提供:ErrorService,useClass:SpecialErrorService}

PS:我想發表此評論,但我不允許這樣做。 說我需要50點聲望...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM