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

时间:2016-10-24 15:46:53

标签: 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){
                    console.log('The value for index is: ' + $scope.userActivity[$scope.index]);
                })
                .error(function(data, status){
                    console.log(data);
                });
            }
        })

我得到“索引的价值是:未定义”,这让我疯了!

由于

2 个答案:

答案 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))
}