2017-01-11 13 views
0

我想從我的API中刪除一個對象。刪除功能起作用,我可以將它從API和存儲在視圖中顯示的對象數組中移除。Angular2視圖不更新,以反映我剛剛從數組(表)刪除的對象(行)

我在我的控制器中有這個刪除方法,當點擊該行中的刪除按鈕時被調用。

onDelete(category) { 
let index = this.categories.indexOf(category); 

if (confirm("Are you sure you want to delete this row?")) { 
    this.categoryService.deleteCategory(category.id) 
    .then(category => { 
     this.categories.splice(index, 1); 
    }); 
} 

}

類別是從HTML模板傳遞的對象。

 <td><button class="icon-myfont-48" value="X" (click)="onDelete(category)"></button></td> 

如果我在this.categories.splice(index,1)之前做了一個console.log(this.categories)然後我在我的數組中看到7個對象,並且如果我之後使用console.log,我會看到6.所以拼接正在工作,它將從數組中刪除我的數據,但我必須刷新頁面或導航到另一個頁面以獲取查看更新。

我在這裏錯過了什麼?我已經嘗試使用ApplicationRef.tick()和ChangeDetectorRef.detectChanges()來強制更新視圖,但目前沒有任何工作。任何幫助表示讚賞。謝謝!

+0

嘗試使用過濾器並完全替換數組。類似於這個代碼片段的東西可能是:'this.categories = this.categories.filter((c)=> c.id!= category.id);' – JacobS

+0

嘿,這工作!我只是從視圖中傳入category.id而不是整個對象,並且在您提供的代碼片段中使用「id」而不是category.id。 非常感謝你! – bmdilla

+0

酷!那麼我會把它移到一個答案 – JacobS

回答

0

嘗試使用過濾器並完全替換陣列。可能與此代碼段相似:

this.categories = this.categories.filter((c) => c.id != category.id); 
相關問題