我正在開發一個電子商務應用程式,它的前端是用 Angular 13 制作的。
以下代碼旨在匯總購物車中商品的價格:
import { Component, OnInit } from '@angular/core';
@Component({
selector: '.app-top-cart',
templateUrl: './top-cart.component.html',
styleUrls: ['./top-cart.component.css']
})
export class TopCartComponent implements OnInit {
cartItems: any = [
{
id: 1,
title: "iPhone 9",
description: "An apple mobile which is nothing like apple",
price: 549,
discountPercentage: 12.96,
rating: 4.69,
stock: 94,
brand: "Apple",
category: "smartphones",
thumbnail: "https://dummyjson.com/image/i/products/1/thumbnail.jpg",
images: [
"https://dummyjson.com/image/i/products/1/1.jpg",
"https://dummyjson.com/image/i/products/1/2.jpg",
]
},
{
id: 2,
title: "iPhone X",
description: "SIM-Free, Model A19211 6.5-inch Super Retina HD display with OLED technology A12 Bionic chip with ...",
price: 899,
discountPercentage: 17.94,
rating: 4.44,
stock: 34,
brand: "Apple",
category: "smartphones",
thumbnail: "https://dummyjson.com/image/i/products/2/thumbnail.jpg",
images: [
"https://dummyjson.com/image/i/products/2/1.jpg",
"https://dummyjson.com/image/i/products/2/2.jpg",
]
}
];
constructor() { }
totalPrice: number = 0;
doTotalPrice(){
let total = 0,
this.cartItems.forEach((item: { price: number, quantity: number; }) => {
total = item.price * item.quantity
}),
this.totalPrice = total,
}
ngOnInit(): void {
this.doTotalPrice();
}
}
問題
上面的代碼無法編譯。它在方法關閉Argument expression expected的第 54 行給出錯誤。doTotalPrice
我的錯誤在哪里?
uj5u.com熱心網友回復:
doTotalPrice(){
let total = 0,
this.cartItems.forEach((item: { price: number, quantity: number; }) => {
total = item.price * item.quantity
},
this.totalPrice = total,
}
您沒有關閉您的函式,而是使用逗號而不是分號。
doTotalPrice(){
let total = 0,
this.cartItems.forEach((item: { price: number, quantity: number; }) => {
total = item.price * item.quantity
});
this.totalPrice = total;
}
獎金,更清潔的代碼:
this.totalPrice = this.cartItems.reduce(
(p, { price, quantity }) => p price * quantity,
0
);
uj5u.com熱心網友回復:
您必須洗掉 forEach(); 之后的逗號;
yourArray.forEach(element=>{
//do something
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/480875.html
標籤:javascript 有角度的 打字稿 角13
