角度材料表中未显示数据

时间:2021-06-07 18:15:02

标签: angular typescript angular-material

我无法使用带角度的材料表生成数据。

这是组件

export class CertificateTableComponent {

  dataSource: MatTableDataSource<any>;
  //certificates: ValueEntity[] = [];
  data: CertificateRow[] = [];
  columns: string[] = ['name', 'id', 'type', 'publicCertificate'];

  @ViewChild(MatSort, { static: true }) sort: MatSort;
  @ViewChild(MatPaginator, { static:true }) paginator: MatPaginator;

  constructor(private _integrationAccountService: integrationAccountService) {
  }

  ngOnInit() {

    this._integrationAccountService.getcertificates().subscribe(response => {
      //this.certificates = response.data;
      this.data = [];
      if (response.value) {
          for (let entity of response.value) {
              let row: CertificateRow = {
                  name: entity.name,
                  id: entity.id,
                  type: entity.type,
                  publicCertificate: entity.properties?.publicCertificate
              };
          }
      }

      this.dataSource = new MatTableDataSource(this.data);
      this.dataSource.sort = this.sort;
      this.dataSource.paginator = this.paginator;

    })

  }
}

这是表:

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

    <ng-container matColumnDef="name">
      <th mat-header-cell *matHeaderCellDef mat-sort-header>Name</th>
      <td mat-cell *matCellDef="let row">{{ row.name }}</td>
    </ng-container>

    <ng-container matColumnDef="id">
      <th mat-header-cell *matHeaderCellDef mat-sort-header>Id</th>
      <td mat-cell *matCellDef="let row">{{ row.id }}</td>
    </ng-container>

    <ng-container matColumnDef="type">
      <th mat-header-cell *matHeaderCellDef mat-sort-header>Type</th>
      <td mat-cell *matCellDef="let row">{{ row.type }}</td>
    </ng-container>

    <ng-container matColumnDef="publicCertificate">
      <th mat-header-cell *matHeaderCellDef mat-sort-header>Public Certificate</th>
      <td mat-cell *matCellDef="let row">{{ row.publicCertificate }}</td>
    </ng-container>

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

  </table>

在控制台中检查时,我可以看到响应值是正确的,但 dataSource 始终显示为空。不确定将数据传递到表时缺少什么。

1 个答案:

答案 0 :(得分:1)

您的代码看起来不错(至少对我而言),只是您忘记将构造的对象添加到 data array 列表中。

     this.data = [];
     if (response.value) {
          for (let entity of response.value) {
              let row: CertificateRow = {
                  name: entity.name,
                  id: entity.id,
                  type: entity.type,
                  publicCertificate: entity.properties?.publicCertificate
               };
               this.data.push(row);      // add here
           }
       }

快乐编码.. :)