无法使用AngularJS更新变量

cannot update variable using AngularJS

本文关键字:更新 变量 AngularJS      更新时间:2023-09-26

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