AngularJS 和 $http.get 中的 Foreach 循环

Foreach loop in AngularJS and $http.get

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

建立服务调用列表,然后调用 $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;
    });
});

我建议你使用$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) 的承诺。