【问题标题】:Injecting service for another service为另一个服务注入服务
【发布时间】: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


【解决方案1】:

在提供服务时,您可以用特殊服务代替它。 例如,如果您在组件中使用它,您可以像这样提供它:

{ 提供:ErrorService,useClass:SpecialErrorService }

PS:我想将此作为评论发布,但我不被允许。说我需要 50 声望...

【讨论】:

    猜你喜欢
    • 2013-12-22
    • 1970-01-01
    • 1970-01-01
    • 2014-01-27
    • 1970-01-01
    • 2023-03-11
    • 2023-03-16
    • 2012-08-01
    相关资源
    最近更新 更多