我使用 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!."));
});
}
你应该看看异步请求和承诺是如何工作的。要使代码运行,您可以执行以下操作: 变量承诺 = [];创建一个数组来存储承诺
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
您可以将类别数组映射到承诺数组中,然后使用$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!."));
});
});
}