Angular2 视图未更新以反映我刚刚从数组(表)中删除的对象(行)



我正在尝试从我的API中删除一个对象。删除函数有效,我可以将其从 API 和存储它的对象数组中删除以显示在视图中。

我的控制器中有这个删除方法,单击行中的删除按钮时调用该方法。

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 个对象,如果我在之后控制台.log我看到 6 个。所以拼接正在工作,它正在从数组中删除我的数据,但我必须刷新页面或导航到另一个页面才能更新视图。

我在这里错过了什么?我尝试使用ApplicationRef.tick()和ChangeDetectorRef.detectChanges()来强制更新视图,但到目前为止没有任何效果。任何帮助,不胜感激。谢谢!

尝试使用过滤器并完全替换数组。类似于这个代码片段的东西可能:

this.categories = this.categories.filter((c) => c.id != category.id);

最新更新