【问题标题】:Angular refresh table after delete record, using material table and rest api删除记录后的角度刷新表,使用材料表和rest api
【发布时间】:2026-01-26 05:50:01
【问题描述】:

我有一个带有可扩展行的材料表 (https://material.angular.io/components/table/examples),我想管理对表本身的删除操作,因此我创建了一个删除按钮,该按钮具有触发删除事件的功能。 api有效,记录被正确删除,但删除后表没有刷新,我想实现这个行为。这是一个带有假 api 的堆栈闪电战:https://stackblitz.com/edit/angular-comzph

我尝试在我的删除函数中调用 ngOnInt 并导航回同一条路线,但没有任何反应...

deleteCustomer(id) {
 this.api.deleteCustomer(id)
  .subscribe(res => {
    alert(`cliente rimosso`);
    // TODO fix reload list after delete
    // this.router.navigate['/clienti'];
    this.ngOnInit();
  }, (err) => {
    console.log(err);
  }
 );
}

我尝试使用this solution too,但不起作用。我尝试使用 ngOnChange 和 ngOnDestroy,但也不起作用...

有人可以帮我吗?

【问题讨论】:

  • 您可以通过调用您的 api 再次获取数据来刷新表数据集,而不是完全刷新或重新初始化组件。
  • 我也尝试在deleteCustomer() 方法中调用this.api.getCustomers(),但不起作用
  • 也许使用管道? this.api.deleteCustomer(id).pipe(flatMap(_ => this.api.getCustomers)).subscribe(result => { // Assign to data })
  • 不,不工作。 datasource 传递给 mat-table html 的属性可能存在问题
  • 我用这个解决方案解决了这个问题:*.com/questions/46746598/…,谢谢你的帮助

标签: angular rest angular-material refresh http-delete


【解决方案1】:

Angular 文档显示有一个方法 renderRows() 可用于 <table mat-table> 元素。我遇到了同样的问题,实现了这个方法,效果很好。我还了解到,您可以选择提供数据流而不是简单数据。下面解决了简单数据行的渲染。

在您的 HTML 模板中,给 <table mat-table> 元素一个属性绑定:

<table mat-table [dataSource]="data" #myTable> <!-- #table binding here -->
  <!-- table cells content etc... -->
</table>

在你的组件类中,用@ViewChild链接到模板属性,当表格数据发生变化时调用renderRows()方法。

import { MatTable } from '@angular/material/table';

export class MyComponent {
    @ViewChild('myTable') myTable: MatTable<any>; /*not exatly sure what the type should be set too */

    editDataMethod(){
        /* data handling logic */
        this.myTable.renderRows();

}

【讨论】:

    【解决方案2】:

    无需调用服务器获取更新数据并重新下载所有数据。只需调用此函数(如下)并删除数据源中的行(拼接)。从您的删除函数中传入记录 id,无论列名是您的 id 所在的位置,然后魔术就会发生。我包括分页器。

    我的StackBlitz for Angular Material Table 有一个工作示例。另请参阅我用于创建和更新的UpdateDatatableService

    // Remove the deleted row from the data table. 
    // Need to remove from the downloaded data first.
    
      private deleteRowDataTable (recordId, idColumn, paginator, dataSource) {
        this.dsData = dataSource.data;
        const itemIndex = this.dsData.findIndex(obj => obj[idColumn] === recordId);
        dataSource.data.splice(itemIndex, 1);
        dataSource.paginator = paginator;
      }
    

    【讨论】:

      【解决方案3】:

      我解决了每次刷新客户列表时为 mat-table 创建一个新数据源的问题。我需要将ChangeDetectorRef 提供给我的构造函数,然后编写此代码:

      refreshCustomersList() {
       this.api.getCustomers()
        .subscribe(res => {
          console.log(res);
          this.clienti = res;
          this.dataSource = new ClientiDataSource(this.api);
          this.changeDetectorRefs.detectChanges();
        }, err => {
          console.log(err);
       });
      }
      

      它有效!

      注意:仅当您使用 mat-table 数据源时才会出现此问题

      【讨论】: