为另一个服务注入服务

Injecting service for another service

本文关键字:服务 注入 另一个      更新时间:2023-09-26

我有几个相互调用的服务级别,即ComponentService使用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:我想把这个作为评论发布,但我不被允许。