【发布时间】:2017-10-04 17:16:45
【问题描述】:
我有几个级别的服务相互调用,即使用 DataService 的 ComponentService 使用 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");
}
}
【问题讨论】:
-
请添加演示您尝试完成的代码。
-
为什么不直接将构造函数参数设为
ConsoleErrorService? -
@GünterZöchbauer - 我对常规和特殊行为都使用完全相同的 DataService。
-
如果
SpecialDataService和RegularDataService在不同的组件中提供,或者在延迟加载的模块中至少提供一个,其中为DataService注册了不同的提供程序,则可以这样做。否则我看不到使用 DI 配置的方法。 -
数据服务是相当大的一段代码,我不想复制 - 我正在尝试使用当前的 DI 设置来获得它。
标签: javascript angular typescript dependency-injection