访问foreach中的注入服务 - angular2

时间:2016-05-04 02:20:54

标签: dependency-injection angular

我有一个有服务的组件注入它的构造函数,我在对象数组上有一个map函数。当我尝试在map函数中访问我的模型时,它返回了未定义的错误。

代码:

export class StrategyComponent implements ComponentDefinition{
type = "component";
strategies : any[];

constructor(@Inject(GateDataModel) private gateDataModel){
   //Updatedcode
   EmitterService.get("event_name")
        .subscribe(obj => {
            this.buildStrategies(obj.strategies);
        })
}


buildStrategies(_strategies){
    this.strategies = _strategies;
}

selectStrategy(i){ //Function called on click from template
    this.gateDataModel.strategyId = this.strategies[i].id;
    this.strategies.map(function(_strategy, index){
        this.gateDataModel.strategyId = _strategy.id; //Error Here
        i === index ? _strategy.isSelected = true : _strategy.isSelected = false;
    })
}


}

如何在地图功能中访问我的模型?

由于

1 个答案:

答案 0 :(得分:1)

正如我在评论中提到的,我非常确定问题在于调用' 这个 .gateDataModel.strategyId'在回电里面。无法在该范围内解析this。您有两种选择:

  1. 陷阱this就像这样:
  2. 
    selectStrategy(i){ //Function called on click from template
        this.gateDataModel.strategyId = this.strategies[i].id;
        var _this = this;
        this.strategies.map(function(_strategy, index){
            _this.gateDataModel.strategyId = _strategy.id; //Error Here
            i === index ? _strategy.isSelected = true : _strategy.isSelected = false;
        })
    }
    
    1. 您可以使用函数指针箭头函数表达式代替:
    2. 
      selectStrategy(i){ //Function called on click from template
          this.gateDataModel.strategyId = this.strategies[i].id;
          this.strategies.map((_strategy, index) => {
              this.gateDataModel.strategyId = _strategy.id; //Error Here
              i === index ? _strategy.isSelected = true : _strategy.isSelected = false;
          }) // You might need to check my syntax
      }