gpt4 book ai didi

javascript - 如何将增量索引值传递给 $http.get

转载 作者:行者123 更新时间:2023-11-29 16:46:40 25 4
gpt4 key购买 nike

如何将增量值传递给 $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);
});
}
})

我收到“索引的值是:未定义”这让我抓狂!

谢谢

最佳答案

问题是,当您的第一个(实际上是所有)成功 回调触发时,$scope.index 将具有值 5 大概在 $scope.userActivity 数组的范围之外。

解决这个问题的一种方法是使用 IIFE

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

另一个 StackOverflow Q/A 将为您提供更深入的细节:JavaScript closure inside loops – simple practical example

关于javascript - 如何将增量索引值传递给 $http.get,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40222482/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com