Vincent Tang Vincent Tang - 22 days ago 8
AngularJS Question

$windows.localStorage reset when I call setItem() after I refresh the page

The outputThe following is my

AddToCart
factory:

.factory('AddToCart', function ($window) {
var products = {};
products.list = [];

return {
addProduct: function (_sku, _image, _name, _price, _quantity, _remark) {
return products.list.push({
id: products.list.length,
sku: _sku,
image: _image,
name: _name,
price: _price,
quantity: _quantity,
remark: _remark
});
},
updateProduct: function (_id, _sku, _image, _name, _price, _quantity, _remark, _show) {
return products.list[_id] = {
id: _id,
sku: _sku,
image: _image,
name: _name,
price: _price,
quantity: _quantity,
remark: _remark,
show: _show
};
},
saveProduct: function () {
$window.localStorage.setItem("CartProducts", JSON.stringify(products.list));
},
getLocalStorageProduct: function () {
return JSON.parse($window.localStorage.getItem("CartProducts"));
}
}
});


I call them this:

AddToCart.addProduct(....); //save in list
AddToCart.saveProduct(); //save to local storage


Then I output the saved items:

AddToCart.getLocalStorageProduct(); //output the list items


OK, It works perfect so far

The problem is when I reload the page and call the
AddProduct()
and
SaveProduct()
, the local storage just reset the data stored before and start with storing the item from
id1
. How can I storing the data without resetting the data before??? Any idea to solve or other method to replace the local storage?

Answer

Based on the screenshot attached by you, you are trying to save the products in the local storage with Key CartProducts. I am not 100% sure but the issue is that you are overriding the current value of CartProducts every time with out checking that if there is already an item in it. In the save function you should first check if there is any item present with the key CartProducts and if its there than you should fetch the current array, convert to JSON and push the new object in the array. Now you should save it.

Try with code like this for saving product.

saveProduct: function () { 

        var cartProducts = JSON.parse(localStorage.getItem("CartProducts")));

        if(cartProducts == null)
        {
          $window.localStorage.setItem("CartProducts", JSON.stringify(products.list)); 
        }
        else
        {
          for(int i = 0; i < products.list, i++)
          {
             cartProducts.push(products.list[i]);
          }

          $window.localStorage.setItem("CartProducts", JSON.stringify(cartProducts)); 
        }

}, 
Comments