Reputation: 4671
I have a factory service to control a shopping cart and I'm will problems to sync the data with controller when I'm still configurating the shopping cart.
the process consists of analyzing whether or not the user is logged. If he is not, then spCart = 0
, if he is logged, then I'll have to make other verifications. Let's say I have 2 more verifications to do:
If user doesn't have valid address, then spCart = 1
;
If he has an address and is whitin the range,
spCart = [
'items':[], //add items here
cost: '0'
];
Or if isn't in the range:
spCart = [
'items':[], //add items here
cost: '9.99'
];
The problem is, some of these verifications needs to wait for a $http
, this way I'm not able to sync the spCart
value from the factory, with the controller. This is what I did:
controller:
function CartController(factCart) {
var sp = this;
factCart.initialLoad();
sp.cart = factCart.getCart();
};
factory:
function factCart (localStorageService,factMain) {
var spCart = 0;
var service = {
initialLoad: _initialLoad,
getCart: _getCart
};
return service;
function _initialLoad() {
var userData = localStorageService.cookie.get(ngApp);
if (userData) {
var func = 'load_address';
factMain.methodGet(func).then(function(res){ //$http from main factory
if(res==0) {
return spCart = [1];
} else {
_checkRange(res);
}
});
} else if (!userData) {
return spCart;
};
};
function _checkRange(data) {
spCart = [];
spCart['items'] = [];
/*
logic here
*/
if (inRange) {
spCart['costs'] = {
cost: 0;
};
return spCart;
} else {
spCart['costs'] = {
cost: 9.99;
};
return spCart;
};
};
function _getCart() {
return spCart;
};
};
The problem is, the spCart
value is always 0
, it doesn't change when I update it, and I don't know what I can do to solve this issue.
Note: I had this problem when adding items to the shopping cart, the view didn't updated. I solved that issue by using $apply()
. But in this case, i couldn't use $apply
, it said 'Cannot read property...'
Upvotes: 0
Views: 114
Reputation: 4671
I managed to make it work. I don't know if it's the best solution, so I'll keep the question opened.
But I had to keep the initial array just like I want it to be when all the verifications are OK and added an extra field to control everything.
So I'll have an array like this:
spCart = [];
spCart['address'] = {
verification: 0,
address: 'name of address',
//..etc..
};
spCart['items']= [];
//..Rest of array - for checkout only
This way the data inside the verification
is being updated. It's not the best way (or at least not how i expected) because I'm exposing the whole array, instead of a single value.
So, if there is a better solution, it will be very welcome.
Upvotes: 0