Angular 7 : Sorting Mat-Table with data from service as a MatTableDataSource

标签 angular rxjs

我正在尝试在 Angular 7 中对表格 MatSort 进行排序,并且是 Angular 的新手。数据在数据源中并正确显示。我的数据来 self 调用后端的服务,然后我设置 this.dataSource.sort = this.sort,如以下示例所示:

https://stackblitz.com/angular/qlbmkgjnvya?file=main.ts (来自 Angular 文档!)

我尝试按照 Angular 文档中的示例进行操作,但我觉得我遗漏了一些东西,因为排序对我的示例没有任何作用,但是当我采用他们的示例并在本地使用它时,它工作正常。

//组件

    import {MatSort} from '@angular/material/sort';
    ...
    dataSource: MatTableDataSource<any[]>;
    @ViewChild(MatSort) sort: MatSort;
    ...
    ngOnInit() {
    this.api.getData().subscribe(data => {
      this.data= data; // this is an array of the data
      this.dataSource = new MatTableDataSource(this.data); // works enough to display on the page without errors
      this.dataSource.sort = this.sort; // has to be in here to ensure no race condition between the api call and setting the sort property
   });

// View (组件.html)

<table mat-table #table [dataSource]="dataSource" matSort>

  <!-- Title Column -->
  <ng-container matColumnDef="id">
    <th mat-header-cell *matHeaderCellDef mat-sort-header> data ID </th>
    <td mat-cell *matCellDef="let element" class="id-col"> {{element.dataID}} </td>
  </ng-container>

  <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
  <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>

没有显示错误消息,但表没有更新。

最佳答案

如果您的数据名称与您的列名称不匹配,则排序函数不知道要对哪些数据进行排序,因此它最终什么都不做(?)并且不会抛出错误。不知道为什么我没有早点想到这一点。

关于 Angular 7 : Sorting Mat-Table with data from service as a MatTableDataSource,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56729006/

相关文章:

angular - 在 Angular 2 中处理嵌套订阅的正确方法

Angular rxjs : access parameter on http error inside pipe/concatMap?

node.js - rxjs 订阅返回重复项

angular - RXJS 获取 ReplaySubject 的当前值

angular - 指示正在进行异步验证的类

angular - RxJS:如何定义(可选)请求的(最大)持续时间?

Angular 2 或 4 : How to add multiple instances of a child component

javascript - 具有多种方法的 Angular 事件

angular - 重试 Observable 时更改 HTTP header

javascript - 发出单个值