Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
949 views
in Technique[技术] by (71.8m points)

javascript - localstorage not updated after refresh angular

After I refresh my browser to retrieve data from localstorage and update that data, it's not updated. But when I add new items and update it, it is updating. What's seems to be the problem here?

//----- update existing item's subtotal in localstorage
        
   changeSubtotalOfExisting(qty ) {

       let updateQty = JSON.parse(localStorage.getItem('cart_items'));
         updateQty['qtyTotal'] = qty;
        localStorage.setItem("cart_items", JSON.stringify(updateQty));
        console.log('updateQty: ', updateQty );
    }

Here's a stackblitz sample: https://stackblitz.com/edit/angular-ivy-i8kpub?file=src/app/app.component.ts

question from:https://stackoverflow.com/questions/65950530/localstorage-not-updated-after-refresh-angular

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There were several problems with your implementation. Failing to save to local storage was only one of them. I ended up rewriting a lot of it, and actually simplifying considerably. I apologize if this was not your intention in your question. Here is the resulting project: https://stackblitz.com/edit/angular-cart-local-storage. You can compare the 2 projects.

I'm listing here some key issues:

  1. Accessing local storage should be done only from the service, not from the component. The service is in charge of saving and retrieving data. The component is in charge of interacting with the user.

  2. You saved to local storage the wrong objects (and maybe this is the answer to your original question). Local storage should store the cart (a list of items). Here for example you're trying to save to local storage as if it stores only one item at a time:

    updateQty['qtyTotal'] = qty; localStorage.setItem("cart_items", JSON.stringify(updateQty));

  3. Your event handlers are called with the wrong arguments. You need to call them with the item as an argument, not the HTML element. Instead of changeSubtotal($event.target, addedItem.variationCost,i) I call changeSubtotal(item ,i)

  4. You did not prevent the user from adding the same item to the cart multiple times.

  5. The initial quantity of an item you add to the cart should be 1 and not 0, as you set the minimum of the quantity control to 1


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...