Angular MatTableDataSource不向dataSource提供数据

时间:2019-05-10 15:19:29

标签: angular

我正在尝试创建一个mat表并从API中获取数据。所以我的服务代码如下

     getAll(){
       return this.http.get<Apps[]>(this.ROOT_URL + 'testcases/');
      }

    getTCbyAppName(appName: any){
        return this.http.get<Apps[]>(this.ROOT_URL + 'testcases/get/'+ appName)
     }   

和我的ts文件

    dataSource = new MatTableDataSource<Apps>();
    displayedColumns = ['App Name', 'noOfTCs']

    fetchTableData(event: any) {
          console.log("Selected App: " + event);
          this.selected = event;
          this.tableVisibility = "visible";
   if (event == "all") {
          this.testcaseService.getAll().subscribe(result => {
          this.dataSource.data = result as Apps[];
        })
   } else {
        this.testcaseService.getTCbyAppName(event).subscribe(result => {
        this.dataSource.data = result as Apps[];
       })
   }

   }

html文件

    <table mat-table [dataSource]="dataSource" class="mat-elevation-z8" [style.visibility]="tableVisibility">

  <!-- Position Column -->
  <ng-container matColumnDef="App Name">
        <th mat-header-cell *matHeaderCellDef> App Name </th>
        <td mat-cell *matCellDef="let apps"> {{apps.appName}} </td>
  </ng-container>

  <!-- Name Column -->
  <ng-container matColumnDef="noOfTCs">
        <th mat-header-cell *matHeaderCellDef> Testcases Count </th>
        <td mat-cell *matCellDef="let apps"> {{apps.noOfTCs}} </td>
  </ng-container>

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

输出仅显示列名。该api工作正常,我不确定为什么matTableDataSource无法正常工作

注意:我正在使用Angular 7

1 个答案:

答案 0 :(得分:0)

向数据源添加或删除数据时,请确保呈现表格,以便角度材质将显示来自数据源的已更新的新数据。

首先,使用ViewChild获得对该表的引用

@ViewChild(MatTable) table: MatTable<any>;

例如,一旦进行了添加或删除操作,就放置此代码

this.dataSource.data = result as Apps[];
this.table.renderRows();

有关更多详细信息:https://material.angular.io/components/table/overview