【发布时间】:2017-08-29 17:44:54
【问题描述】:
我正在尝试在 Angular2 中实现 addtoCart 功能。 我正在使用 typescript 类来表示 LineItem,它表示产品以及数量和总价(数量 * 产品价格)。
export interface Product {
id?: number;
name?: string;
price?: number;
}
订单项:
export class LineItem {
product: Product;
quantity: number;
totalPrice: number;
}
订单项数组:
lineItems: LineItem[];
在添加到购物车功能中,我想检查该项目是否已添加,如果是,则只需找到与该产品对应的订单项并更新该特定订单项。
我选择的方法是: - 找到索引。 - 如果 >-1 则添加新的行项目。 - 否则编辑订单项。
问题是:当我尝试查找索引时,它显示此错误
Cannot read property 'id' of undefined
代码是:
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);
}
}
第一次调用没有错误,第二次调用抛出错误。 这是问题所在:
const index = this.lineItems.findIndex( (item) => {
return item.product.id === product.id
});
item.product.id 抛出:无法读取未定义的属性“id”。
是否有打字稿类或接口或任何逻辑错误。
【问题讨论】:
-
你确定不是
product.id在扔吗?那是在同一条线上。您是否记录了item、item.product和product的值以查看其中的内容?这似乎是调试时要尝试的第一件事。我们没有您的任何数据,因此很难判断。 -
在控制台中记录你的 lineItems,看看你会得到什么。
标签: javascript angular