如何将增量值传递到$ http.get函数中。请参阅下面的代码段:
for($scope.index=0 ; $scope.index < 5 ; $scope.index++)
{
$http.get('/api/post', {params: { id: $scope.userActivity[$scope.index].post }})
.success(function(res){
console.log('The value for index is: ' + $scope.userActivity[$scope.index]);
})
.error(function(data, status){
console.log(data);
});
}
})
我得到“索引的价值是:未定义”,这让我疯了!
由于
答案 0 :(得分:3)
问题在于,当您的success
回调消息$scope.index
首次(实际上是全部)时,5
的值$scope.userActivity
可能超出{{for($scope.index=0 ; $scope.index < 5 ; $scope.index++)
{
(function(i){
$http.get('/api/post', {params: { id: $scope.userActivity[i].post }})
.success(function(res){
console.log('The value for index is: ' + $scope.userActivity[i]);
})
.error(function(data, status){
console.log(data);
});
}
})
})($scope.index);
}
范围之内1}}数组。
解决此问题的一种方法是使用IIFE
Swift 3.0
此其他StackOverflow Q / A将为您提供更深入的详细信息:JavaScript closure inside loops – simple practical example
答案 1 :(得分:2)
Closures
要营救您的index
与$scope.userActivity
for ($scope.index = 0; $scope.index < 5; $scope.index++){
(function(i) {
$http.get('/api/post', {
params: {
id: $scope.userActivity[$scope.index].post
}
})
.success(function(res) {
console.log('The value for index is: ' + $scope.userActivity[$scope.index]);
})
.error(function(data, status) {
console.log(data);
});
}($scope.index))
}