【问题标题】:Foreach loop in AngularJS and $http.getAngularJS 和 $http.get 中的 Foreach 循环
【发布时间】:2015-09-08 18:59:45
【问题描述】:

我的 AngularJS 函数有问题。来自第一个 forEach 的数据使用 $http.get 检索,而在第二个 forEach 中,$scope.products 尚未定义。我知道$http.get() 是一个异步请求,这就是重点……但是如何重写这个函数才能正常工作?

$scope.getAll = function () {
    var cookies = $cookies.getAll();
    $scope.products = [];
    var i = 0;
 angular.forEach(cookies, function (v, k) {
     console.log("important1:" +  $scope.products);
        console.log("key: " + k + ", value:  " + v);
         ProductsService.retrieve(k).then(function(response) {
                    $scope.products = $scope.products.concat(response.data);
                        $scope.products[i].quantity = v;
                        i++;
         }, function (error) {
            console.log('error');
         });
  });
    console.log("important2:" +  $scope.products);

    angular.forEach($scope.products, function(value, key) {
        $scope.total = value.quantity*value.price + $scope.total;
        console.log("Quantiy: " + value.quantity);
        console.log("Price: " + value.price);
    });
    console.log($scope.products);
    console.log($scope.total);
};

【问题讨论】:

  • 将所有ProductsService.retrieves 放入promise 数组中并使用$q.all([promises]).then(...) 解决。

标签: angularjs get


【解决方案1】:

我建议你使用$q.all()

更具体地说,你会这样做:

$q.all([p1, p2, p3...]).then(function() {
    // your code to be executed after all the promises have competed.
})

其中 p1, p2, ... 是与您的每个 ProductsService.retrieve(k) 对应的承诺。

【讨论】:

    【解决方案2】:

    建立一个服务调用列表,然后调用 $q.all。在 then 函数中,您可以放置​​第二个循环。

    var listOfServiceCalls = [];
    //Add to list of service calls
    
    $q.all(listOfServiceCalls)
        .then(function () {
            //All calls completed THEN
                angular.forEach($scope.products, function(value, key) {
            $scope.total = value.quantity*value.price + $scope.total;
        });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-09
      • 1970-01-01
      • 2016-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多