Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular HTTP Get on loop [duplicate]

I have an issue with an Angular app.

I have an array that contains langs shortcodes ('en', 'fr', ...). And basically, I want Angular to loop on that array and make HTTP get request on each value.

for (var i in $scope.langs) {
      console.log($scope.langs[i].shortName);
      $http.get($scope.appURL + $scope.langs[i].shortName + '/api/products/?format=json&resto='+ $scope.restoID)
         .then(function(res){
            $scope.products = angular.fromJson(res.data);   
            window.localStorage.setItem("products-"+$scope.langs[i].shortName, JSON.stringify(res.data));
            $scope.products =  JSON.parse(window.localStorage.getItem("products-"+$scope.langs[i].shortName));
            console.log('LANG = '+ $scope.langs[i].shortName, $scope.products);
          });
}

The first log shows :

fr
en

Great ! The last log is thrown twice (I've got 2 langs in my array), great too.

The problem is that in the loop, the log shows the same language in both case, when I should have one fr/api/... and one en/api/... It always log 2 en/api/...

I don't know if it's clear... Any idea ?

like image 412
enguerranws Avatar asked Jun 05 '14 16:06

enguerranws


1 Answers

The problem is that your i variable changes before all your ajax requests return. Therefore, it will always be equal to the $scope.langs.length - 1 when your callback executes. You're going to want to create a closure around each of your $http requests. Angular has some built in functionality for just that:

angular.forEach($scope.langs, function(lang){
  // Here, the lang object will represent the lang you called the request on for the scope of the function
  $http.get($scope.appURL + lang.shortName + '/whatever/you/want', function(res) {
    // Do whatever you want with lang here. lang will be the same object you called the request with as it resides in the same 'closure'
    window.localStorage.setItem(lang.shortName, JSON.stringify(res.data));
  });
});
like image 170
Mike Quinlan Avatar answered Nov 12 '22 22:11

Mike Quinlan