2

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.

2
  • Are you sure it's not product.id that's throwing? That's on the same line. Have you logged the values of item, item.product and product to 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. Commented Aug 29, 2017 at 17:50
  • Log your lineItems in console and see what you get there. Commented Aug 29, 2017 at 17:55

1 Answer 1

-1
const lineItem: LineItem = Object.assign({}, product);

This line result as a plain object :

lineItem = {ProductID: 1, ProductName: "Chai", UnitPrice: 18, quantity: 2}

So there is no item.product.id object chain its simple plain object

PLUNKER

Sign up to request clarification or add additional context in comments.

1 Comment

lineItem is type of LineItem, not Product. And product is not an array, so this is basically wrong: this.lineItems.product.push(lineItem);

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.