角度材料表不显示数据

JDS*_*JDS 3 angular-material angular

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

验证数据:

<pre>{{ myData| json }}</pre>
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

打字稿:

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)
    ); } 
}
Run Code Online (Sandbox Code Playgroud)

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

接口

export interface IMyData {
  id: string;
  path: string;
  date: Date;
  location: Geolocation;
  name: string;
  gizmos: string[];
}
Run Code Online (Sandbox Code Playgroud)

示例数据:

[
  {
    "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"
    ]
  }
]
Run Code Online (Sandbox Code Playgroud)

Tom*_*ula 6

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

更改 <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));
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 我试过了,但它仍然对我不起作用。在我的情况下,我猜测在数据可以实际填充行之前以某种方式加载了网格行。 (2认同)