アイテムは前にカートに追加されました。今、私はこの既存のアイテムの値を更新したいと思います。 addToCart関数では、findItem()関数はカートをチェックし、既存の項目への参照を返します。アイテムが存在するので、findItem()関数から返された既存のアイテムをnewItemに割り当てます。これはexistingItem = newItemです。カートに入っているexistingItemはnewItemの値を持つことになりますが、カート内のアイテムを印刷すると、existingItemはnewItem値ではなく以前の値を持ちます。角2:参照渡しのオブジェクトが正常に動作しない
export class CartItem {
product: Product;
quantity: number;
itemTotal: number;
color: string;
protectionPlan: string;
}
export class Cart {
total: number = 0;
numberOfItems: number = 0;
items: CartItem[] = [];
findItem(id: String) : CartItem {
for(let i=0; i < this.items.length; i++) {
if(this.items[i].product._id == id) {
console.log("*************** item found ********************")
return this.items[i];
}
}
return null;
}
addItem(newItem: CartItem) {
let existingItem: CartItem = this.findItem(newItem.product._id);
if(existingItem) {
existingItem = newItem;
//existingItem.quantity = newItem.quantity;
console.log("update item id = " + existingItem.product._id);
console.log("update item quantity = " + existingItem.quantity);
console.log("update item color = " + existingItem.color);
console.log("update item protectionPlan = " +
existingItem.protectionPlan);
} else {
this.items.push(newItem);
this.numberOfItems++;
}
console.log("cart = " + JSON.stringify(this.items));
}
}
を取る(特にフロントエンドのフレームワークで)使用することができます。 existingItem = newItemを削除します。 quantityプロパティを少なくとも変更する必要があります –
existingItem = newItemは、カート内に既に存在するアイテムに新しいアイテムの値を割り当てる方法です。私がそれを取り除くと、カート内のアイテムは新しい値を取得しません。 – koque
本当に、私の答えをチェック;) –