gpt4 book ai didi

Angular Material 表不显示数据

转载 作者:太空狗 更新时间:2023-10-29 18:15:12 29 4
gpt4 key购买 nike

我错过了什么?我已验证我的 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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com