2017-08-11 21 views
-1

的項目以前添加到購物車不能正常工作。現在我想更新這個現有項目的值。在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)); 
    } 
} 
+0

程序的當前行爲實際上是所預期的。刪除existingItem = newItem;並且數量屬性至少應該更改 –

+0

existingItem = newItem是如何將新項目的值分配給購物車中已有的項目。如果我刪除它,購物車中的物品不會獲得新的值。 – koque

+0

不是,查看我的答案;) –

回答

1

這行代碼:

let existingItem: CartItem = this.findItem(newItem.product._id); 

是創建所指向的數組中的項的實例。

這行代碼:

existingItem = newItem; 

正在改變這種情況下,以指向新的項目。

它不是替換爲新項目的陣列中的項目。

你要麼需要每個元素在新項目複製到現有項目或從陣列中刪除現有的項目,並添加新項目。

enter image description here

+0

謝謝,德博拉。這工作。 – koque

1

這更多的是一個OOP相關的問題。生病試圖解釋儘可能明確:

讓我們從這裏開始:

addItem(newItem: CartItem) { 
    let existingItem: CartItem = this.findItem(newItem.product._id); 
    if(existingItem) { 
    ... 
    } 
} 

當你進入if塊,你將有兩個不同的指針參考兩幅,可能是不同的對象。

當你做到以下幾點:

existingItem = newItem; 

你現在有兩個指針引用同一個對象。 所以基本上,做這樣的事情:

existingItem.quantity = newItem.quantity; 

沒有任何效果,因爲你將覆蓋一個值與自身。

至於要變異現有對象的值,一個方法可行辦法是使用Object.assign如下:

if(existingItem) { 
    Object.assign(existingItem,newItem); 
} 

但在我看來,變異列表的內部狀態是怎麼樣的醜陋。保持你的對象不變在大多數情況下好東西。因此,不同的方法會是以下幾點:

addItem(newItem: CartItem) { 
    let index = //some function that gives you the index in the array where the existing item is, or -1 if not present 
    if(index!=-1) { 
     items.splice(index,1,newItem); // there is another approach with the .filter operator 
     this.items = [...items];// see spread operator 
    } else { 
     this.items = [...items,newItem]; // see spread operator 
     this.numberOfItems++; // this is kinda silly, as items.length would give you this value 
    } 

}

這樣你創建的每一個元素被更新或添加時間新的列表

有關不變性以及如何一些額外的信息都可以使用(特別是在前端框架)來看看here!