Reputation: 4317
In my Angular App i have a list of object which i can add to the cart, when an item is added to the cart i'm saving the cart in local storage, the issue is that if the item is added from the product detail (where the item image is a large image) soon i will get localstorage error which will say that it's memory is ended.
So i would manage it in the way that when an item is added from item detail i would set it's image to null and then when the user change it's route to cart i'd call an API to get the images for all products without the image.
The issue is that my function to add the item to the cart in my cart service looks like this:
addToCart(product: Plu, big_image?: boolean): any{
if (big_image) {
product.img = null;
}
this.carrello.plu.push({ ...product});
this.cartTotal();
}
But as the product: Plu is a ref the image of actual Plu in the detail item page will be set to null too..
So which would be the best solution to set the Plu image to null before adding it to this.carrello.plu
?
I was thinking about something like this:
addToCart(product: Plu, big_image?: boolean): any{
const clone = Object.assign({}, product);
if (big_image) {
clone.img = null;
}
this.carrello.plu.push({ ...clone });
this.cartTotal();
}
But i would know if it's the best solution...
Upvotes: 2
Views: 63
Reputation: 1013
You can simply do something like this:
addToCart(product: Plu, big_image?: boolean): any{
const clone = {
...product,
img: big_image ? null : product.img
};
this.carrello.plu.push(clone);
this.cartTotal();
}
Spread operator works like Object.assign
Reference: https://basarat.gitbook.io/typescript/future-javascript/spread-operator
Upvotes: 1
Reputation: 71
You can do like this:
addToCart(product: Plu, big_image?: boolean): any{
this.carrello.plu.push({ ...product, img: big_image ? null : product.img});
this.cartTotal();
}
Also small remark: don't use null
in Angular and Typescript, better use undefined
Upvotes: 1