Javascript 如何将增量索引值传递给$http.get
如何将增量值传递到$http.get函数中。请参见下面的代码片段:Javascript 如何将增量索引值传递给$http.get,javascript,angularjs,Javascript,Angularjs,如何将增量值传递到$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){
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);
});
}
})
($scope.index=0;$scope.index<5;$scope.index++)的
{
$http.get('/api/post',{params:{id:$scope.userActivity[$scope.index].post}})
.成功(功能){
log('索引的值为:'+$scope.userActivity[$scope.index]);
})
.错误(功能(数据、状态){
控制台日志(数据);
});
}
})
我得到了“索引的值是:未定义的”,这让我抓狂
谢谢问题是,当您的
成功
回调启动$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);
}
($scope.index=0;$scope.index<5;$scope.index++)的
{
(职能(一){
$http.get('/api/post',{params:{id:$scope.userActivity[i].post})
.成功(功能){
log('索引的值为:'+$scope.userActivity[i]);
})
.错误(功能(数据、状态){
控制台日志(数据);
});
}
})
})($scope.index);
}
另一个StackOverflow Q/A将为您提供更深入的详细信息:
闭包
要拯救,您的索引
,它与$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))
}
($scope.index=0;$scope.index<5;$scope.index++)的{
(职能(一){
$http.get('/api/post'{
参数:{
id:$scope.userActivity[$scope.index].post
}
})
.成功(功能){
log('索引的值为:'+$scope.userActivity[$scope.index]);
})
.错误(功能(数据、状态){
控制台日志(数据);
});
}($scope.index))
}
谢谢你的回答,伙计。正如我在上面的评论中所说,它成功了。高度赞赏