javascript - $windows.localStorage reset when I call setItem() after I refresh the page -
the following
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 local storage
then output saved items:
addtocart.getlocalstorageproduct(); //output list items
ok, works perfect far
the problem is when reload page , call addproduct()
, saveproduct()
, local storage reset data stored before , start storing item id1
. how can storing data without resetting data before??? idea solve or other method replace local storage?
based on screenshot attached you, trying save products in local storage key cartproducts. not 100% sure issue overriding current value of cartproducts every time out checking if there item in it. in save function should first check if there item present key cartproducts , if there should fetch current array, convert json , push new object in array. should save it.
try code saving product.
saveproduct: function () { var cartproducts = json.parse(localstorage.getitem("cartproducts")); if(cartproducts == null) { console.log("cartproducts == null"); $window.localstorage.setitem("cartproducts", json.stringify(products.list)); } else { console.log("cartproducts != null"); for(var = 0; < cartproducts.length; i++) { products.list.push(cartproducts[i]); } $window.localstorage.setitem("cartproducts", json.stringify(products.list)); } //$window.localstorage.setitem("cartproducts", json.stringify(products.list)); },
Comments
Post a Comment