1

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;
    });
}
jose
  • 1,044
  • 1
  • 12
  • 35
  • 1
    You should probably post a bit more, oh also if you actually use + Stream that variable is not defined here, why not use the i there too – Mathijs Segers May 10 '17 at 05:21
  • Problem is, by the time all your HTTP requests finish, `i` is and will only be the value `4` – Phil May 10 '17 at 05:31
  • Possible duplicate of [JavaScript closure inside loops – simple practical example](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – Phil May 10 '17 at 05:32
  • you need to learn javascript at first, instead of start from angular... –  May 10 '17 at 05:48

3 Answers3

2

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);
Community
  • 1
  • 1
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
1

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);
}
Raghu Venmarathoor
  • 858
  • 11
  • 28
1

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));
}
Pengyy
  • 37,383
  • 15
  • 83
  • 73