In my angular project have a shopping cart feature. Soi wants some help from anyone.
Angular 7 cli
constructor(private cartService:CartServicesService)
public addToCart(productId : any , productTypeStatus:any , quantityCount:any ){
var cartProductData = {
"productId": productId,
"productSelectedTypeId": productTypeStatus,
"productQuantity": quantityCount
};
this.cartService.addToCart(cartProductData); //send data to cart-service.ts
}
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class CartServicesService {
constructor() { }
public addToCart(cartData:any) {
console.log(cartData);
//save data in local storage------------------------------------
localStorage.setItem('cartObject', JSON.stringify(cartData));
}
}
Key : cartObject
Value : {"productId":3,"productSelectedTypeId":null,"productQuantity":4}
Well, the steps you have mentioned on your question, are generally correct. However, I would recommend you to store it as an array of objects, instead of just an object on its own.
This is how you can get the cart data from your localStorage.
let cart = JSON.parse(localStorage.getItem('cartObject'));
Then, we use Array.some() to check if the new item on your shopping list exists on the cart from cartObject
.
let isInCart = false;
if (cart) {
isInCart = cart.some(item => item.productId ===
cartProductData.productId));
} else {
cart = [];
}
Then, we handle it based on isInCart
, which is a boolean value that denotes if the item exists on the cart:
if (isInCart) {
cart.map(item => {
if (item.productId === cartProductData.productId) {
item.productQuantity += cartProductData.productQuantity;
}
return item;
});
} else {
cart.push(cartProductData);
}
Then, we store the updated cart
on your localStorage:
localStorage.setItem('cartObject', JSON.stringify(cart));