0

I am building small utility to handle shopping cart of user in AngularJS.

Below is my cart-service.js file definition.

var myStoreCartService = angular.module("myStoreCartService", []);

myStoreCartService.factory('Cart', function() {
    var userCart=[];
    var cartSummary=[];

    return{

        addItemToCart: function(item) {
            userCart.push(item);  
        },  

        retrieveCart: function(){
            return userCart;
        },

        getCartSummary: function(){
            cartSummary=[];
            for (var key in userCart){
                var currentItem={"productname":"","price":""};              
                if (userCart.hasOwnProperty(key)){                      
                    currentItem["productname"]=userCart[key].productname;
                    currentItem["price"]=userCart[key].price;
                    cartSummary.push(currentItem);
                    continue;
                };
            }
            return cartSummary;
        },

        getCurrentTotal: function(){
            alert("Sum function called "+ cartSummary);
            var currentSum=0;
                for (var key in cartSummary)
                {  
                    if (cartSummary.hasOwnProperty(key))
                    {    
                        // get sum     
                        currentSum = currentSum+parseInt(cartSummary[key].price);
                        alert(currentSum+" is current sum")
                        continue;
                    };
                }
            return currentSum;
        }

    }

});

Below is method used to update the cart of page.(Defined in controller of page)

function addItemToCartHelper(data){
  Cart.addItemToCart(data);  
  $scope.cart=Cart.retrieveCart();
  $scope.cartLength=$scope.cart.length;
  $scope.userCartSummary=Cart.getCurrentTotal();
  $scope.userCartSummaryFromService=Cart.getCartSummary();
}

My issue is I am not getting correct total sum of the price ,I always get one less item added to my price.

I do realize that, my function to sum the total cost should run only after my cart summary has been updated , but in my case it runs before cart summary update function has been launched.

I need a way to ensure that, cart summary has finished execution before totaling function runs.

4
  • Can't you just reverse the order of the last two statements in addItemToCartHelper then...? They're both synchronous calls as far as I can tell. Commented Jul 14, 2014 at 3:12
  • That may solve issue if I just have few items in cart and cart summary doesn't need much processing. If cart summary was complex function , it may not yet have finished execution. Commented Jul 14, 2014 at 4:39
  • I need something which is similar to call-back . Cart Summary should execute and in call-back of it get total should execute. Commented Jul 14, 2014 at 4:40
  • Did the below solution worked for you ? Commented Jul 30, 2014 at 5:06

1 Answer 1

1

For the case you mentioned the best approach you can use is the Promise API ($q) service provided by Angularjs. It is used for synchronizing, asynchronous tasks. Like with your case

The Promise API is used to fulfill a promise when a condition is satisfied i.e resolved or rejected.

You can use .then from promise created by deferred object using $q.defer()
Example :

var deferredObject = $q.defer();
var deferredPromise = deferredObject.promise;
deferredPromise.then(successCallback,errorCallback);

deferredObject.resolve() // Calls the successCallback
deferredObject.reject() // Will call errorCallback

For better explanation follow the link - http://andyshora.com/promises-angularjs-explained-as-cartoon.html

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.