我的角度控制器遇到了一个令人沮丧的问题。我试图有条件地设置附加到我的作用域的对象的某些字段的值。下面的if
块本身可以很好地工作,但是一旦添加了else
块,就会遇到以下错误:
TypeError: Cannot assign to read only property 'gameType' of true
var getGames = function() {
var defer = $q.defer();
playersService.getGames({
playerId: playerId
}).$promise.then(function(data) {
vm.games = data;
for (var x in vm.games) {
if (vm.games[x].activity_type === 'preseason') {
vm.games[x].gameType = 'preseason';
} else {
vm.games[x].gameType = vm.games[x].type;
}
}
defer.resolve(data);
});
return defer.promise;
};
在console.log
'ing vm.games[x]
在else
块中之后,当我点击:
Promise {$$state: Object}
true
...whereas所有其他行显示:
Resource {id: "...", ...}
发布于 2015-08-18 07:52:38
不要在数组上使用for in
循环,而是使用标准的for
循环。for in
用于迭代对象的属性。这可能会导致分配属性值时出现一些问题。
发布于 2015-08-18 07:30:30
您的vm.games[x].gameType
数据类型和vm.games[x].type;
数据类型可能有所不同。
如果您的if条件运行良好,那么您可以尝试
if (vm.games[x].activity_type === 'preseason') {
vm.games[x].gameType = 'preseason';
} else {
vm.games[x].gameType = ''+ vm.games[x].type; // ''+ is convert to string
}
https://stackoverflow.com/questions/32076245
复制