0

I am trying to send multiple $http request, the request is in .service:

app.service('servlet', function($http){
    var base = "http://myUrl.com" // real url is private
     //queryParams for GET request
    this.sendGet = function(queryParams){
    var promise = $http({method:'GET', url:base, params:queryParams}).then(
     (function(response){
       return response.data;     
    });
    return promise; // var promise 
  }
});

Calling sendGet() work fine and returns a promise but when I use it in a loop :

console.log($scope.items.length) // 5
for(var i =0 ; i<scope.items.length; i++){
//scope.items - query params
console.log(scope.items[i]);
  servlet.sendGet(scope.items[i]).then(function(data){
   console.log(i);
 });
};

the log show :

object{param1 : 1} //scope.items[i]
object{param2 : 2} //scope.items[i]

and then the console.log(i) - inside the servlet in the loop.

[4]5
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Itsik Mauyhas
  • 3,824
  • 14
  • 69
  • 114
  • Need to realize that the loop completes far sooner than the requests so `i` will always be maximum. Reason is explained here http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example. What exactly are you wanting to do? – charlietfl Apr 17 '16 at 14:05
  • call the request several times with diffrent params, the result is data from different DB's. – Itsik Mauyhas Apr 17 '16 at 14:06
  • That part of the loop should be working...passing different `scope.items[i]` into the service call on each iteration. You will have a problem accessing correct `i` inside callback though unless you use a closure. See above link – charlietfl Apr 17 '16 at 14:07
  • I did not understant the how does the post is realted to my question? – Itsik Mauyhas Apr 17 '16 at 14:09
  • The proper requests will be made. It's what you want to do with responses that you haven't specified. Read and understand that link and use `angular.forEach()` instead of `for` loop to create closure – charlietfl Apr 17 '16 at 14:10
  • Insert the data into a table, but it is sending only one request each time... – Itsik Mauyhas Apr 17 '16 at 14:11
  • Need to concatenate results from each request into a scope array – charlietfl Apr 17 '16 at 14:12

0 Answers0