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
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
you can map your array of categories into an array of promises and then use
$q.all
to wait for them all to finish