I am trying to implement addtoCart function in Angular2. I am using typescript class to represent a LineItem which is to represent product along with quantity and total price ( quantity * product price).
export interface Product {
id?: number;
name?: string;
price?: number;
}
Line items:
export class LineItem {
product: Product;
quantity: number;
totalPrice: number;
}
Array of Line items:
lineItems: LineItem[];
In add to cart function, I want to check if the item is already added, if so just find the line item corresponding the product and update that specific line item.
Method I am choosing is: - find the index. - if it is >-1 then add the new line item. - else edit the line item.
Issue is: When I am trying to find the index it shows this error
Cannot read property 'id' of undefined
code is :
addProductToCart(product: any, quantity: number) {
const lineItem: LineItem = Object.assign({}, product);
lineItem.quantity = quantity;
lineItem.totalPrice = product.price * quantity;
const index = this.lineItems.findIndex( (item) => {
return item.product.id === product.id
});
if(index > -1) {
// edit the current item .
this.lineItems[index].quantity = quantity;
this.lineItems[index].totalPrice = quantity * product.price;
}else {
this.lineItems.push(lineItem);
}
}
no error on first call, second call throws error. this is the problem line:
const index = this.lineItems.findIndex( (item) => {
return item.product.id === product.id
});
item.product.id throws : Cannot read property 'id' of undefined.
is it something with typescript class or interface or any logical error.
product.idthat's throwing? That's on the same line. Have you logged the values ofitem,item.productandproductto see what's there? That would seem to be the first thing to try when debugging. We don't have any of your data, so it's pretty hard to tell.