2016-05-20 15 views
4

私は角度1.5を使用します。私はカテゴリーを照会する関数を持っています。それから各カテゴリーについて、それは商品を照会します。私はすべての製品が回収された後にメッセージを表示したいが、回収された製品の数は表示されたい。 0を出力します。解決策は何ですか?

function getProducts() { 
    vm.categories = []; 
    var prodcount = 0; 

    $http.get("localhost/menu/1/categories") 
    .then(function(response) { 
     var categories = response.data; 
     angular.forEach(categories, function(cat) { 
     $http.get("localhost/category/" + cat.id + "/products") 
      .then(function(response) { 
      cat.products = response.data; 
      vm.categories.push(cat); 
      prodcount += cat.products.length; 
      }); 
     }); 
     $mdToast.show($mdToast.simple().textContent("retrieved " + vm.categories.length + " categories and, " + prodcount + " products!.")); 
    }); 
} 
+1

を終了するのを待つために$q.allを使用することができますあなたの製品?これは本当に奇妙に見えますし、確かにあなたのパフォーマンスに影響を与えます – MayK

+1

多くの約束を待つのに '$ q.all'を使うことができます。http://stackoverflow.com/questions/23931846/wait-for-all-http-requests 〜完全な角度のjs。また、あなたのサーバーを飽和させないために、次のコールを実行する前に、すべてのコールが完了するのを待つことができます。もちろん、クライアント側のループではなく、1つのサーバー・コールですべてを取り出すことが最善です。 – floribon

+1

私はいつもAJAX要求を持つ「プロバイダ」をAngularで使用してきました。 – circusdei

答えて

1

非同期要求と約束がどのように機能するかを見てください。 コードを実行するには、次のようにします。 var promises = []; //約束を格納する配列を作成する

angular.forEach(categories, function(cat) { 

    // Capture the promise 
    var requestPromise = $http.get(...) 
    .then(function(response) { 
     ... 
    }); 
    promises.push(requestPromise); // Add it to the array 
    }); 

    // This promise will be resolved when all promises in the array have been resolved as well. 
    $q.all(promises).then(function(){ 
    $mdToast.show(...); 
    }) 

}); 

しかし、この方法はあまり良くありません。あなたは要求の量を最小限にしようとするべきです。

http://www.martin-brennan.com/using-q-all-to-resolve-multiple-promises/ http://andyshora.com/promises-angularjs-explained-as-cartoon.html

1

あなたは約束の配列にカテゴリのあなたの配列をマッピングして、あなたはすべてを取得するエンドポイントを持っていないそれらすべてが

function getProducts() { 
    vm.categories = []; 
    var prodcount = 0; 

    $http.get("localhost/menu/1/categories") 
      .then(function (response) { 
       var categories = response.data; 
       $q.all(categories.map(function (cat) { 
        return $http.get("localhost/category/" + cat.id + "/products") 
          .then(function (response) { 
           cat.products = response.data; 
           vm.categories.push(cat); 
           prodcount += cat.products.length; 
          }); 
       })).then(function() { 
        $mdToast.show($mdToast.simple().textContent("retrieved " + vm.categories.length + " categories and, " + prodcount + " products!.")); 
       }); 
      }); 
} 
+0

が働いた!ありがとう。 – nurp