我有一个有服务的组件注入它的构造函数,我在对象数组上有一个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;
})
}
}
如何在地图功能中访问我的模型?
由于
答案 0 :(得分:1)
正如我在评论中提到的,我非常确定问题在于调用' 这个 .gateDataModel.strategyId'在回电里面。无法在该范围内解析this
。您有两种选择:
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;
})
}
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
}