无法在角材表格中显示数据

时间:2018-10-16 15:04:31

标签: angular material-design

使用角形材料设计数据表,我需要从REST API中获取数据并在表中显示响应。

但是在表中显示数据时出现问题。

Modal.ts

export interface ReleaseModal {
    results: [{
        id: number;
        title: string;
    }]
} 

Service.ts

  getReleaseNotes(): Observable<ReleaseModal[]> {
      return this.http.get<ReleaseModal[]>(this.url);
  } 

component.ts

export class ReleasesComponent implements OnInit, AfterViewInit{
  title = 'Release notes';
  displayedColumns = ['releasenotes'];
  dataSource;

  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;

  constructor ( private releaseNotes: ReleaseService ) {}

  ngOnInit() {
    this.releaseNotes.getReleaseNotes()
    .subscribe(data => {
      this.dataSource = new MatTableDataSource(data);
      console.log(data);
    });
  }

  ngAfterViewInit() {
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;
  }
}

HTML

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

    <ng-container matColumnDef="releasenotes">
      <mat-header-cell *matHeaderCellDef mat-sort-header> Release Notes </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.results.title}}% </mat-cell>
    </ng-container>

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

当我在控制台上记录data时,我可以看到结果,但是不确定为什么它没有显示在表中。请帮助

下面是示例响应,我是通过API调用获得的

{
"results": [
{
"id": "203901655",
"title": "Test Page",
},
....
}

2 个答案:

答案 0 :(得分:1)

按如下所述更改ngOnInit,应对其进行修复:

dispalyedColumns=['title']
ngOnInit() {
    this.releaseNotes.getReleaseNotes()
    .subscribe(data => {
      this.dataSource = new MatTableDataSource(data.results);
      this.dataSource.paginator = this.paginator;
      this.dataSource.sort = this.sort;
      console.log(data);
    });
}

删除ngAfterViewInit中的行。问题是因为ngAfterViewInit在从服务中获取数据之前被调用,而dataSource仍未定义。

HTML:    

<ng-container matColumnDef="title">
  <mat-header-cell *matHeaderCellDef mat-sort-header> Release Notes </mat-header-cell>
  <mat-cell *matCellDef="let row"> {{row.title}}% </mat-cell>
</ng-container>

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

答案 1 :(得分:0)

尝试这个:

export class ReleasesComponent implements OnInit, AfterViewInit{
  title = 'Release notes';
  displayedColumns = ['releasenotes'];
  dataSource = new MatTableDataSource<ReleaseModal>();

  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;

  constructor ( private releaseNotes: ReleaseService ) {}

  ngOnInit() {
    this.releaseNotes.getReleaseNotes()
    .subscribe(data => {
      this.dataSource.data = data;
      console.log(data);
    });
  }

  ngAfterViewInit() {
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;
  }
}