I have an angular application that implements factory functions to handle some API requests for a global object that is implemented in almost all controllers.
factory.loadCart = function() {
var deferred;
deferred = $q.defer();
httpService.get({
service: 'cocacola',
param1: 'userCart',
guid: sessionStorage.token
}, function(r) {
if (r.error == 0) {
$rootScope.user.cart = r.result;
deferred.resolve(r.result);
} else {
deferred.reject("Error al cargar el carrito.")
}
}, function(errorResult) {
deferred.reject(errorResult);
});
return deferred.promise;
}
In the code I set the value of user.cart property as the result of the request. When I go to another controller that also implements this factory method (in this way)...
CartFactory.loadCart().then(function(response) {
$rootScope.user.cart = response;
$scope.cart = $rootScope.user.cart;
if ($rootScope.user.cart.productos.length == 0) {
$state.go('main.tienda');
} else {
getCards();
$rootScope.showCart = false;
}
}, function(error) {
$scope.loading = false;
$scope.showMe = false;
$state.go('main.tienda');
console.log(error);
});
... and go back to the first controller, the user.cart property is undefined and I can't proceed to execute the other functions that are defined as factory methods since the $rootScope.user.cart property is undefined and required as a parameter to these other functions. Also, the $rootScope.user.cart property gets its value after I refresh the browser (but I can't keep this as a solution), I'm very new to Angular so any help will be really appreciated, this is driving me nuts!
I've always found that $rootScope was somewhat difficult to work with, and something of an antipattern in AngularJS... it's like putting variables on the global scope in vanilla JS.
Is there any reason you wouldn't avoid the whole $rootScope.user.cart issue by just keeping cart in CartFactory and then putting an API in CartFactory to getCart, then return whatever cart is to any interested controller?