[英]Filter on object in array
在 Angular 項目中,我試圖從數組中刪除一個對象,為此需要過濾數組,然后將該數組替換到存儲中(在本例中為電容器/存儲)
我的功能:
deleteArticle(id: string): void {
this.order = this.order[0].filter(p => p.products.productKey !== id);
}
訂單:訂單; ==>
export interface OrderProduct {
productKey: string;
productName: string;
price: number;
}
export interface Order {
key?: string;
customerKey: string;
products: OrderProduct[];
country?: string;
city?: string;
postcode?: string;
addressLine?: string;
creationDate?: any; //date
}
在 HTML 中點擊:
<ion-col>
<ion-button (click)="deleteArticle(p.productKey)">
<ion-icon name="trash-outline"></ion-icon>
</ion-button>
</ion-col>
單擊按鈕時,我可以看到數組就像預期的那樣,與我要過濾的 ID 相同,但我不斷收到此錯誤:
無法讀取未定義的屬性(讀取“過濾器”)
如果 order 在您編寫時屬於 Order 類型並且您嘗試this.order[0].filter...
您嘗試訪問 this.order 的名為“0”(如“零”)的屬性,該屬性很可能是未定義的因此沒有過濾方法。 從我看到的你可以刪除'[0]'並且它可以工作。 沒有更多的代碼只是一個猜測。
我找到了解決方案,這是一個數據類型的東西:)
需要將產品添加到 this.order...
async deleteArticle(id: string): Promise<void> {
this.order.products = this.order.products.filter(p => p.productKey !== id);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.