首页 > 解决方案 > Angular 5:材料表数据不会在从不同组件触发时更新

问题描述

我正在研究 Angular 5,在更新 mat-table(Angular Material 数据表)时遇到问题。

有 2 个独立组件(没有父子组件)我正在更改一个组件中下拉列表的值,并尝试根据该值从数据库中获取值并因此更新数据表。

在调试时,我发现更新的数据来自数据库,但我在数据表中看不到任何更新。

可能有一些与 mat-table 相关的问题,但不确定。

提前致谢。

下面是我用来从数据库中获取数据并绑定数据表的代码。

async GetFileHistoryDataBasedOnRole(selectedRole: string) {

    let fileHistoryDataBasedOnRole: any = await this.fileHistoryService.FetchFileHistoryDataBasedOnRole(selectedRole);

    if (fileHistoryDataBasedOnRole != undefined && fileHistoryDataBasedOnRole != null) {
      fileHistoryDataBasedOnRole = JSON.parse(fileHistoryDataBasedOnRole.toString());
      this.dataSource = new MatTableDataSource(fileHistoryDataBasedOnRole);
      this.dataSource.paginator = this.paginator;
      this.dataSource.sort = this.sort;
    }
  }

标签: angulardatatableangular-material

解决方案


为自己创建一个最小的例子:

以异步流的形式提供数据,您可以订阅以进行调试。过滤器的每次更改,都应该重新触发订阅块。如果您已经成功地完成了这项工作,那么下一步就是将此数据放入数据源中。

接下来要解决的问题是确保在数据源更改时创建一个新对象(数组)。正如您在示例中看到的,如果您只是数据推送到数组中,您的表永远不会知道数据有更新。

因此,创建一个新数组(方法 add)并扩展它。这将重新渲染表格:

https://stackblitz.com/edit/angular-1erfob?file=app/table-basic-example.html


推荐阅读