环路角HTTP GET [英] Angular HTTP Get on loop
问题描述
我有带角度的应用程序的问题。
I have an issue with an Angular app.
我有一个包含LANGS短codeS ('恩','fr'包,...)阵列。基本上,我要角到阵列上环和使用HTTP GET每个值要求
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);
});
}
第一日志显示:
fr
en
大!最后的日志被抛出两次(我有我的阵列2 LANGS),太伟大。
Great ! The last log is thrown twice (I've got 2 langs in my array), great too.
的问题是,在循环中,日志显示了两种情况下,当我应该有相同的语言,只需一FR / API / ...和一个带/ API / ...它随时登录2 EN / API /...
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 ?
推荐答案
的问题是,你的 I
所有Ajax请求之前变量的变化返回。因此,它总是等于 $ scope.langs.length - 1
回调执行时。你将要创建周围每个的封闭 $ HTTP
请求。角有内建的功能对于这一点:
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));
});
});
这篇关于环路角HTTP GET的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!