我是 AngularJS 的新手,我正在尝试使用 .foreach 循环发送 http 请求。这是我的代码
app.controller('myCtrl', function($scope, $http) {
var rd;
$http.get(furl,config).then(function mySucces(response) {
rd = response.data;
var webcontent = "";
angular.forEach(rd, function(rd1){
$http.get(furl1 + rd1.slug,config).then(function(res){
webcontent += res.data.title;
console.log(webcontent);//console 1
});
});
console.log(webcontent);//console 2
$scope.myWelcome = webcontent;
}, function myError(response) {$scope.myWelcome = response.statusText;});});
我预计控制台 2 将显示组合的“res.data.title”,但是,它只显示初始值。(在本例中为空)。控制台日志 1 显示正确 - 列出不断增加的“webcontent”变量。 不确定如何保持“webcontent”(控制台 2)更新值。任何回应将不胜感激!谢谢!
最佳答案
这不是一个 Angular 问题,这是一个异步 JavaScript 问题。你的代码在你的 promise 完成之前就完成了。您可以使用查询库等待所有 promise 得到解决,如下所示:
app.controller('myCtrl', function($scope, $http, $q) {
var rd;
$http.get(furl, config).then(function mySucces(response) {
rd = response.data;
var webcontent = "";
var promises = [];
angular.forEach(rd, function(rd1) {
promises.push($http.get(furl1 + rd1.slug, config);
});
$q.all(promises).then(function (results) {
angular.forEach(results, function (result) {
webcontent += result.data.title;
}
$scope.myWelcome = webcontent;
});
}, function myError(response) {
$scope.myWelcome = response.statusText;
});
});
关于javascript - 无法使用 AngularJS 更新变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36652792/