使用MatTableDataSource时,Firebase的角度材质表为空

时间:2018-04-26 18:03:20

标签: angular firebase datatable firebase-authentication angular-material

当我在桌面上使用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);
        });
    });

}

1 个答案:

答案 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;

        });
    });

}