我使用Angular 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!."));
});
}
答案 0 :(得分: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 :(得分:1)
您可以将您的类别数组映射到一组承诺中,然后使用$q.all
等待它们全部完成
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!."));
});
});
}