I have problem with my AngularJS function. Data from first forEach is retrieved with $http.get and in second forEach, $scope.products isn't defined yet. I know that $http.get() is an asynchronous request and this is the point... But how to rewrite this function to work fine ?
$scope.getAll = function () {
var cookies = $cookies.getAll();
$scope.products = [];
var i = 0;
angular.forEach(cookies, function (v, k) {
console.log("important1:" + $scope.products);
console.log("key: " + k + ", value: " + v);
ProductsService.retrieve(k).then(function(response) {
$scope.products = $scope.products.concat(response.data);
$scope.products[i].quantity = v;
i++;
}, function (error) {
console.log('error');
});
});
console.log("important2:" + $scope.products);
angular.forEach($scope.products, function(value, key) {
$scope.total = value.quantity*value.price + $scope.total;
console.log("Quantiy: " + value.quantity);
console.log("Price: " + value.price);
});
console.log($scope.products);
console.log($scope.total);
};
ProductsService.retrieves in an array of promises and resolve using$q.all([promises]).then(...).