How to use an external variable inside the response from the response of $ http.get

Here is my code

for (var i=0; i<5; i++) {
    var url = generate_url(i) ;
    $http.get(url).then(function(response){
        var param2 = response.data.param2
        $scope.outputData.push({'index':i, 'param':param2}) ;
    }) ;
}

In this example, I intend to get an array in $scope.outputDatawith data similar to this:

[
  {'index':0,param:'a'},
  {'index':1,param:'b'},
  {'index':2,param:'c'},
  {'index':3,param:'d'},
  {'index':4,param:'e'},
]

but I get this data:

[
  {'index':4,param:'a'},
  {'index':4,param:'b'},
  {'index':4,param:'c'},
  {'index':4,param:'d'},
  {'index':4,param:'e'},
]

In this case, the externel data that I mean is a variable i,

Please, could you tell me about the trouble? and how do I get to my goal? Thanks in advance and sorry for my English :)

+4
source share
2 answers

You can create a closure on a variable ito make sure that it still has the value that you want to use when using it.

for (var i=0; i<5; i++) {
    (function(counter) {
        var url = generate_url(i);
        $http.get(url).then(function(response){
            var param2 = response.data.param2
            $scope.outputData.push({'index':counter, 'param':param2}) ;
        });
    }(i));
}

, , index.

$q.all, - , .

- :

var promises = {};
for (var i=0; i<5; i++) {
    var url = generate_url(i) ;
    promises[i] = $http.get(url);
}
$q.all(promises).then(function(result) {
  for (index in result) {
      var param2 = result[index].data.param2
      $scope.outputData.push({'index':index, 'param':param2}) ;
  }
});

.

$q .

+4

,

for (var i=0; i<5; i++) {
   getData(i);
}
var getData=function(index) {
     var url = generate_url(index) ;
    $http.get(url).then(function(response){
        var param2 = response.data.param2
        $scope.outputData.push({'index':index, 'param':param2}) ;
    }) ;
}
+1

Source: https://habr.com/ru/post/1541131/


All Articles