问题描述
我使用Angular 1.5。我有一个查询类别的功能,然后对每个类别,它查询产品。我想在所有产品被检索后显示一条消息,检索了多少条。它输出0.什么是解决方案? function getProducts(){
vm.categories = [];
var prodcount = 0;
$ b $ http.get(localhost / menu / 1 / categories)
.then(function(response){
var categories = response.data;
angular.forEach(类别,功能(猫){
$ 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(retrieve+ vm.categories.length +categories and,+ prodcount +products !.));
}) ;
异步请求和承诺如何工作。
为了让你的代码运行,你可以这样做:
var promises = []; //创建一个数组来存储承诺
angular.forEach(categories,function(cat){
//捕获承诺
var requestPromise = $ http.get(...)
.then(function(response){
...
});
Promises.push(requestPromise); //将它添加到数组
});
//当数组中的所有承诺都被解决的时候,这个承诺将被解决。
$ q.all(promises).then(function(){
$ mdToast.show(...);
})
});
但这种做法不太好。你应该尽量减少请求的数量,最好只做一个。
I use Angular 1.5. I have a function that queries Categories, then for each category, it queries Products. I want to show a message after all the products are retrieved, how many were retrieved. It outputs 0. What is the solution?
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!."));
});
}
You should take a look at how asynchronous requests and promises works.To make your code run you could do this: var promises = []; // Creates an array to store the 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(...);
})
});
But this approach is not quite good. You should try to minimize the amount of requests, doing only one preferably.
http://www.martin-brennan.com/using-q-all-to-resolve-multiple-promises/http://andyshora.com/promises-angularjs-explained-as-cartoon.html
这篇关于递归$ http.get for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!