AngularJS和$ http.get中的Foreach循环

时间:2015-09-08 18:59:46

标签: angularjs 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);
};

2 个答案:

答案 0 :(得分: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)对应的承诺。

答案 1 :(得分:0)

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