[英]Injecting service for another service
我幾乎沒有服務級別可以互相調用,即ComponentService
使用DataService
,而DataService
使用ErrorService
。
現在,組件服務之一需要指定DataService
使用的ErrorService
實例應為例如SpecialErrorService
類型。 -並且它不直接使用ErrorService
或SpecialErrorService
。
實例化時,如何指示數據服務注入正確的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.