我对 Angular 应用程序有疑问。
我有一个包含语言短代码的数组(“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 个语言),也很棒。
问题是在循环中,日志在两种情况下显示相同的语言,当我应该有一个 fr/api/... 和一个 en/api/... 时,它总是记录 2 en/api/...
我不知道是否清楚...有什么想法吗?
问题是你的i
在所有 ajax 请求返回之前变量会发生变化。因此,它总是等于$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));
});
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)