当我在桌面上使用MatTableDataSource获取Firebase中的数据时,表格为空。当我将Firebase中的数据保存到变量时,表格工作正常,我不知道发生了什么但是我想使用MatTableDataSource来方便排序,所以如果有人能指出我哪里出错了非常感谢,谢谢!
html片段:
//This will have a populated table
//<mat-table #table [dataSource]="itemList">
//This will have an empty table
<mat-table #table [dataSource]="dataSource">
<ng-container matColumnDef="name">
<mat-header-cell *matHeaderCellDef> Name </mat-header-cell>
<mat-cell *matCellDef="let item"> {{item.name}} </mat-cell>
</ng-container>
...
<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
</mat-table>
ts片段:
itemList: Item[];
...
dataSource = new MatTableDataSource(this.itemList);
// Connect to firebase db with Item Service
constructor(private itemService: ItemService) { }
ngOnInit() {
let data = this.itemService.getData();
data.snapshotChanges().subscribe(item => {
this.itemList = [];
item.forEach(element => {
let json = element.payload.toJSON();
json["$key"] = element.key;
this.itemList.push(json as Item);
});
});
}
答案 0 :(得分:0)
您正在使用async programming 您的订阅将在稍后解决,并且您尝试使用尚未发送的数据初始化数据表。您需要在subscribe
回调中填充数据表,以确保仅在订阅解决时初始化它。请参阅this以便更好地理解。
// Connect to firebase db with Item Service
constructor(private itemService: ItemService) { }
dataSource = new MatTableDataSource(Item[]);
ngOnInit() {
let data = this.itemService.getData();
data.snapshotChanges().subscribe(item => {
this.itemList = [];
item.forEach(element => {
let json = element.payload.toJSON();
json["$key"] = element.key;
this.itemList.push(json as Item);
this.datasource= new MatTableDataSource(this.itemList)
//this.datasource.data=this.itemList;
});
});
}