What I'm trying do is when the user adds item to cart more than once I would like it to be a separate image instead of just adding to the quantity. I have it now where if product exist in the cart it just adds to the quantity. The reason I need this change is because now there are product sizes associate with the product using radio buttons and this won't work the way it currently is. I tried manipulating the code but I still get same result or get cart is empty. Can someone point me in the right direction. I have included code snippet.
cart.service.ts
getCartItems(): Observable<CartItem[]> {
return this.http.get<CartItem[]>(cartUrl).pipe(
map((result: any[]) => {
let cartItems: CartItem[] =[];
for(let item of result) {
let productExists = false
for(let i in cartItems){
if(cartItems[i].productId === item.product.id){
cartItems[i].qty
productExists = true
break;
}
}
if (!productExists){
cartItems.push( new CartItem(item.id,item.product,item.imageUrl));
}
}
return cartItems;
})
);
}
Thanking You In Advance
CodePudding user response:
Are you sure you tried to modify the code? In this chunk you are doing the quantity of the product and setting the flag for pushing or not the item with the image
for(let i in cartItems){
if(cartItems[i].productId === item.product.id){
cartItems[i].qty
productExists = true
break;
}
In this other chunk you literally are reading the flag from the last "for" and pushing if the flag is false
if (!productExists){
cartItems.push( new CartItem(item.id,item.product,item.imageUrl));
}
You can do a for to push all the items without any validations or adding to the "qry"
CodePudding user response:
I took out all the validation like Cayman suggested and now it works the way I need it to for the application. The previous code was checking if exist which I don't need because I want to load another product even if it does exist. Part of previous code is still good for situations when you don't want to add a product that already exist for example a wish list or favorites. Correct code snippet without validation below:
getCartItems(): Observable<CartItem[]> {
return this.http.get<CartItem[]>(cartUrl).pipe(
map((result: any[]) => {
let cartItems: CartItem[] =[];
for(let item of result) {
cartItems.push( new CartItem(item.id,item.product,item.imageUrl));
}
return cartItems;
})
);
}
Hope this can help someone.
PDH