无法使用AngularJS更新变量
cannot update variable using AngularJS
我是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)的更新值。如有任何回应,我们将不胜感激!谢谢
这不是角度问题,而是异步javascript问题。您的代码在您的承诺完成之前完成。您可以使用查询库来等待所有的承诺得到解决,比如:
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;
});
});
您可以完全删除webcontent变量,然后直接在其位置更新$scope.myWelcome
变量,这样就可以工作了。因此:
app.controller('myCtrl', function($scope, $http) {
var rd;
$http.get(furl,config).then(function mySucces(response) {
rd = response.data;
$scope.myWelcome = "";
angular.forEach(rd, function(rd1){
$http.get(furl1 + rd1.slug,config).then(function(res){
$scope.myWelcome += res.data.title;
console.log(webcontent);//console 1
});
});
}, function myError(response) {$scope.myWelcome = response.statusText;});});
Ajax调用总是异步任务,它们类似于window.setTimeout
。不可能一个任务一个任务地编写代码。看看:
console.log(1);
window.setTimeout(console.log.bind(console, 2));
console.log(3);
之所以会发生这种情况,是因为异步任务是在随后的事件循环中执行的(将来)。
最后,您的代码片段可能是这样的:
$http
.get(furl, config)
.then(function(response) { return response.data; })
.then(function(resources) {
return $q.all(resources.map(function(resource) {
return $http.get(furl1 + resource.slug, config);
}));
})
.then(function(results) {
return results.map(function(result) {
return result.data.title;
}).join('');
})
.catch(function(response) {
return response.statusText;
})
.then(function(greetings) {
$scope.myWelcome = greetings;
})
;
相关文章:
- Jquery-每个循环不更新变量
- 函数返回后更新变量
- 我无法通过angularjs中的指令更新变量
- 可以't在quizz页面范围问题上用最终分数更新变量
- 如何在AJAX会话之外更新变量?(Backbone JS/CoffeeScript)
- Javascript 对象方法不更新变量
- 当jquery中的输入发生更改时更新变量
- 无法使用AngularJS更新变量
- 在arr.splice()之后更新变量
- Javascript承诺并更新变量
- jQuery-在输入值更改时更新变量
- 使用数据属性通过 jquery 定位和更新变量
- 从数组中删除不会更新变量内的引用
- 冒泡 从嵌套函数更新变量
- 在 .click 上使用 $.ajax 更新变量
- Javascript - Bootstrap-Slider,如何根据滑块的值更新变量
- JavaScript Ajax 不按时更新变量
- 如何在 JS 中更新变量
- Javascript 没有更新变量
- 在函数中更新变量时,变量不会反映视图中的更新