Angular 为什么在将第二项添加到checkoutList时会获得undefined的cannot read属性?
我正在为某种webshop创建一个checkoutList,我正在尝试创建一个函数,当同一元素被按下两次时,使数量1更高。第一个项目确实添加到checkoutList,但每当添加第二个项目时,控制台中将显示错误“无法读取未定义的属性“0”Angular 为什么在将第二项添加到checkoutList时会获得undefined的cannot read属性?,angular,typescript,Angular,Typescript,我正在为某种webshop创建一个checkoutList,我正在尝试创建一个函数,当同一元素被按下两次时,使数量1更高。第一个项目确实添加到checkoutList,但每当添加第二个项目时,控制台中将显示错误“无法读取未定义的属性“0” export class CheckoutComponent implements OnInit { @Input() checkoutItem: any checkoutItems = [ // {name: "Test1&qu
export class CheckoutComponent implements OnInit {
@Input() checkoutItem: any
checkoutItems = [
// {name: "Test1", amount: 4, price: 100 },
// {name: "test2", amount: 2, price: 20 },
// {name: "test3", amount: 6, price: 50 },
// {name: "test4", amount: 1, price: 8 },
];
checkoutTotal = 0;
constructor(productservice: ProductService, private msg: MessengerService) { }
ngOnInit(): void {
this.msg.getMsg().subscribe((product: Product) => {
this.addProductToCheckoutList(product)
})
}
addProductToCheckoutList(product: Product){
let productExists = false;
for(let i in this.checkoutItems){
if(this.checkoutItems[i].id == product.id){
this.checkoutItem[i].quantity++
productExists = true
break;
}
}
if(!productExists){
this.checkoutItems.push({
id: product.id,
name: product.name,
quantity: 1,
price: product.price
})
}
this.checkoutTotal = 0
this.checkoutItems.forEach(item => {
this.checkoutTotal += (item.quantity * item.price)
})
}
}
我添加了一个图像,以清除页面的外观以及错误的外观。
您可以通过更改
this.checkoutItem[i].数量++代码>
到
this.checkoutItems[i].数量++代码>