Skip to content

Instantly share code, notes, and snippets.

@swallentin
Created November 18, 2015 15:00
Show Gist options
  • Save swallentin/5b9f70973ddcb6665d9e to your computer and use it in GitHub Desktop.
Save swallentin/5b9f70973ddcb6665d9e to your computer and use it in GitHub Desktop.
Have fun!
cramo.service('Cart', function($http, $q, $localStorage) {
var _cart = null,
_items = null,
self = this,
getCart = function(userID) {
var deferred = $q.defer();
if(_cart) {
deferred.resolve(_cart);
} else {
$http({
method: "GET",
url: api.cart.getLocal
})
.success(function(cart) {
if(cart) {
_cart = cart;
deferred.resolve(cart);
} else {
deferred.reject(new Error('Cart response was empty'));
}
})
.error(function() {
deferred.reject(new Error('Error when caling for cart'));
});
}
return deferred.promise;
},
getItems = function() {
var deferred = $q.defer();
if(items) {
deferred.resolve(items);
} else {
items = [];
getCart().then(function(data) {
for (var i = 0; i < data.length; i++) {
items.push(data[i].products.length);
}
deferred.resolve(items);
});
}
getCart().then(function(data) {
for (var i = 0; i < data.length; i++) {
items += data[i].products.length;
}
return items;
deferred.resolve(items);
});
return deferred.promise;
};
return {
items: getItems
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment