user3816378
user3816378

Reputation: 93

How to build an object array by chaining http calls in AngularJS?

I want to build an array of objects but for each object I need multiple chained http calls. Eg:

var objects = [];
$http.get(/getDataUrl)
.then(function(data){
   for(i = 0; i < data.length; i++)
   {
       objects[i] = { value1 : data.value }
   }
   for(i = 0; i < objects.length; i++)
   {
       http.get(objects[i].value1)
       .then(function(data){
           objects[i].value2 = data.value;
       }
   }
})

Any ideas how to properly execute this mess?

Upvotes: 1

Views: 60

Answers (3)

akashrajkn
akashrajkn

Reputation: 2315

You will always get 'i' value to be the final index because the renderer will print it when the ajax request gives 200, this will take some time. And in that short time, the for loop would have been executed, therefore you will always get the last index for the value of 'i'

To solve this, you will have to use, closure inside loops

Modify your code like as follows,

var objects = [];
$http.get(/getDataUrl)
.success(function(data){
   for(i = 0; i < data.length; i++)
   {
       objects[i] = { value1 : data.value }
   }
   for(i = 0; i < objects.length; i++)
   {
       (function(index) {
           var currentURL = objects[i].value1;

           $http.get(currentURL)
           .success(function(data) {

               // both currentURL and i value can be accessed here 
               console.log(currentURL);
               console.log(index); // i value  = index

               objects[index].value2 = data.value;
           });
       })(i);
   }
})

Now you have access of index inside the anonymous function. Hope this helps

Upvotes: 2

aorfevre
aorfevre

Reputation: 5064

Try something like that : Only one loop to rules them all ;)

$http.get(/getDataUrl)
.then(function(data){
   for(i = 0; i < data.length; i++)
   {
       objects[i] = { value1 : data.value }


       $http.get(objects[i].value1)
       .then(function(data){
           objects[i].value2 = data.value;
       }
    }

})

Upvotes: 0

Freezystem
Freezystem

Reputation: 4874

You can try to use success instead of then, as $http isn't a standard promise :

var objects = [];
$http.get('/getDataUrl')
.success(function(data){
   for(i = 0; i < data.length; i++)
   {
       objects[i] = { value1 : data.value }
   }
   for(i = 0; i < objects.length; i++)
   {
       http.get(objects[i].value1)
       .success(function(data2){
           objects[i].value2 = data2.value;
       }
   }
})

Upvotes: 0

Related Questions