jose
jose

Reputation: 1054

http get method is not working in for loop in angularjs

hi all i am using angularjs http get method i get the values dynamically based on my loop but i am not able to get the value from http get help how to do this and solve the problem

for(i=0;i<4;i++){
    var stream =i;
    $http.get('/ViewGetBUMaterialStream/' + stream  ).then(function (response) {
                   $scope.ViewStreams[i] = response.data;
    });
}

Upvotes: 1

Views: 317

Answers (3)

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48357

You can use let keyword. This is a usually problem for closures.

The let statement declares a block scope local variable, optionally initializing it to a value.

for(let i=0;i<4;i++){
    var stream =i;
    $http.get('/ViewGetBUMaterialStream/' + stream  ).then(function (response) {
               $scope.ViewStreams[i] = response.data;
    });
}

Another method is to use a Immediately-invoked function expression.

(function(i){
  $http.get('/ViewGetBUMaterialStream/' + Stream  ).then(function (response) 
     {
        $scope.ViewStreams[i] = response.data;
     });
})(i);

Upvotes: 2

Pengyy
Pengyy

Reputation: 38171

try this to bind i to your callbacks.

for(i=0;i<4;i++){
  var stream =i;
  $http.get('/ViewGetBUMaterialStream/' + stream  ).then(function (response) {
    $scope.ViewStreams[i] = response.data;
  }.bind(i));
}

Upvotes: 1

Raghu Venmarathoor
Raghu Venmarathoor

Reputation: 868

This issue is caused because of javascript. Unfortunately, javascript does not have a scope for a loop, variables declared in a for loop are in a function scope. You should use an anonymous inner function and pass the value of i to that function block.

for(i=0;i<4;i++){
    var stream =i;
    (function(i){
      $http.get('/ViewGetBUMaterialStream/' + Stream  ).then(function (response) {
                   $scope.ViewStreams[i] = response.data;
      });
    })(i);
}

Upvotes: 1

Related Questions