Angular Material 表不显示数据

标签 angular angular-material

我错过了什么?我已验证我的 API 正在返回数据,但是我无法让数据显示在我的表中。

验证数据:

<pre>{{ myData| json }}</pre>

HTML

<div *ngIf="dataSource">
  <mat-table [dataSource]='dataSource'>
    <ng-container matColumnDef="name">
      <mat-header-cell *matHeaderCellDef> Name </mat-header-cell>
      <mat-cell *matCellDef="let df"> {{df.name}} </mat-cell>
    </ng-container>
    <ng-container matColumnDef="path">
      <mat-header-cell *matHeaderCellDef> Path </mat-header-cell>
      <mat-cell *matCellDef="let df"> {{df.path}} </mat-cell>
    </ng-container>

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

  </mat-table>
</div>

typescript :

export class HomeComponent implements OnInit {
  columnsToDisplay = ['name', 'path'];
  myData: IMyData[];
  dataSource = new MatTableDataSource<IMyData>(this.myData);

  constructor(private myDataService: MyDataService) { 
    console.log("IN CONSTRUCTOR");
  }

  ngOnInit(): void {
    this.myDataService.getData()
    .subscribe(x => this.myData = x,
      error => console.log("Error (GetData) :: " + error)
    ); } 
}

编辑:我想知道它是否与我的界面有关:

界面

export interface IMyData {
  id: string;
  path: string;
  date: Date;
  location: Geolocation;
  name: string;
  gizmos: string[];
}

示例数据:

[
  {
    "id": "9653a6b5-46d2-4941-8064-128c970c60b3",
    "path": "TestPath",
    "date": "2018-04-04T08:12:27.8366667",
    "location": "{\"type\":\"Point\",\"coordinates\":[102.0,0.5]}",
    "name": "TestName",
    "gizmos": [
      "AAAA",
      "BBBB",
      "CCCC"
    ]
  }
]

最佳答案

第一个错误是使用单引号而不是双引号的错误数据绑定(bind):

更改 <mat-table [dataSource]='dataSource'>

对此:<mat-table [dataSource]="dataSource">

第二个错误是不正确的数据源初始化。您应该创建 MatTableDataSource从服务中获取数据后。

export class HomeComponent implements OnInit {
  columnsToDisplay = ['name', 'path'];
  dataSource: MatTableDataSource<IMyData>;

  constructor(private myDataService: MyDataService) {   }

  ngOnInit(): void {
    this.myDataService.getData()
     .subscribe(data => this.dataSource = new MatTableDataSource(data));
  }
}

关于 Angular Material 表不显示数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49819585/

相关文章:

node.js - Angular 路线守卫有多安全?

Angular 2在引导之前从服务器获取配置

javascript - Angular 形 Material 底板单击时无法关闭

angular - 为什么 ng build --prod 失败,而 ng build 成功?

css - Angular Material -如何设置垫水平内容容器填充0

带有 Material 选项卡的 Angular 8 - 在重新加载时选择最后一个事件选项卡

angular - 更新所有 Angular 组件

angular - 推送到 FormArray 不会更新 mat-table

typescript - ImmutableJS 如何与 Angular 2 一起工作?

angularjs - 将对象属性拆分为两列