Javascript 角度HTTP进入循环

Javascript 角度HTTP进入循环,javascript,angularjs,Javascript,Angularjs,我有一个角度应用程序的问题 我有一个数组,其中包含langs短码('en','fr',…)。基本上,我希望Angular在该数组上循环,并对每个值发出HTTP get请求 for (var i in $scope.langs) { console.log($scope.langs[i].shortName); $http.get($scope.appURL + $scope.langs[i].shortName + '/api/products/?format=json&

我有一个角度应用程序的问题

我有一个数组,其中包含langs短码('en','fr',…)。基本上,我希望Angular在该数组上循环,并对每个值发出HTTP get请求

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);
          });
}
第一个日志显示:

fr
en
太好了!最后一个日志被抛出两次(我的数组中有2个lang),也很好

问题是,在循环中,日志在两种情况下显示相同的语言,而我应该有一个fr/api/。。。和一个en/api/。。。它总是记录2 en/api/


我不知道是否清楚。。。有什么想法吗?

问题是在所有ajax请求返回之前,
i
变量会发生变化。因此,在执行回调时,它将始终等于
$scope.langs.length-1
。您需要围绕每个
$http
请求创建一个闭包。Angular具有一些内置功能:

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));
  });
});

看起来像是异步问题@不是。问题是,匿名函数中的变量
i
在执行函数时绑定,而不是在创建函数时绑定,并且它将始终具有最后一个键值(即
$scope.langs.length-1
),感谢该链接,我将尝试看看我能用它做些什么。我担心这是一个异步问题,就像Fals所说的。我理解这个问题,通过你给我的链接,我无法独自解决这个问题,我想…我会试试,我不知道angular.forEach,这肯定会帮助我,谢谢!完全解决了我的问题。谢谢