简体   繁体   English

在foreach中访问注入服务-angular2

[英]Accessing Injected service in foreach - angular2

I have a component which has a service Injected into it's constructor and I have a map function on array of objects. 我有一个将服务注入其构造函数的组件,并且在对象数组上有一个map函数。 When I tried access my model inside map function it's returning undefined error. 当我尝试在地图函数中访问我的模型时,它返回未定义的错误。

Code: 码:

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;
    })
}


}

How can I access my model inside map function? 如何在地图功能中访问模型?

Thanks 谢谢

As I mentioned in the comment, I'm pretty sure the problem is calling ' this .gateDataModel.strategyId' inside the call back. 正如我在评论中提到的那样,我很确定问题是在回调内调用了' this .gateDataModel.strategyId'。 this cannot be resolved in that scope. this不能在范围内加以解决。 You have two options: 您有两种选择:

  1. Trap this outside like so: 像这样将其捕获this外部:

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. You can use a function pointer arrow function expression instead: 您可以改用函数指针箭头函数表达式:

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM