首页 > 解决方案 > MatTable 没有从 Observable 填充数据

问题描述

我正在使用 AngularFire 从 firestore 数据库中检索一组文档。在开发人员控制台中,它显示正在获取的数据,但该表未在站点上填充。这是我的服务类:

import { Injectable } from '@angular/core';
import {Observable, of} from 'rxjs';
import { AngularFirestore, DocumentData } from '@angular/fire/firestore';
import { AngularFireAuth } from '@angular/fire/auth';


@Injectable({
  providedIn: 'root'
})
export class DatabaseHandlerService {
  constructor(private afStore: AngularFirestore, private afAuth: AngularFireAuth) {

  }

  // Get my complaints asynchronously
  getMyComplaints(): Observable<Item[]>{

    const usID = this.afAuth.auth.currentUser.uid;
    const newstuff = [];

    this.afStore.collection('user').ref.where('userID','==',usID).get().then(function(snapshot) {
      snapshot.docs[0].ref.collection('mycomplaints').
      get().then(function(snapshot){
        //console.log(snapshot.docs[0].data());
        snapshot.forEach(function(doc){
          newstuff.push(doc.data());
        });  
      });
    });

    return of(newstuff as Item[]);
  }

}

我在我的组件类中订阅 Observable,如下所示:

 ngOnInit() {
    this.getComplaints();
  }

  getComplaints(): void {
    this.handler.getMyComplaints().pipe(debounceTime(20), delay(20)).
    subscribe(data => { 
      this.dataSource = new MatTableDataSource(data);
      console.log(data);
    },error=>{
      console.log(error);
    },()=>{
      console.log('Data fetched');
    });
  }

我尝试使用forkJoin函数而不是 of函数来返回 Observable 但根本没有获取任何数据;在以下链接中建议了forkJoin

编辑:这是 MatTable 的模板文件:

<div class="container mt-5 pb-5">
    <div class="text-center mb-5 mt-5">
        <h1>My Complaints</h1>
    </div>
    <mat-form-field>
        <input matInput (keyup)="applyFilter($event.target.value)" placeholder="Filter">
        <mat-icon matSuffix>search</mat-icon>
    </mat-form-field>

    <mat-table [dataSource]="dataSource" class="mat-elevation-z8">
        <ng-container matColumnDef="badgeNumber">
            <mat-header-cell *matHeaderCellDef> Badge #
            </mat-header-cell>
            <mat-cell *matCellDef="let element"> {{element.badgeNumber}} </mat-cell>
        </ng-container>
        <ng-container matColumnDef="lastName">
            <mat-header-cell *matHeaderCellDef> Last Name
            </mat-header-cell>
            <mat-cell *matCellDef="let element"> {{element.lastName}} </mat-cell>
        </ng-container>
        <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
        <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
    </mat-table>


</div>

标签: angularangular-materialangularfire2

解决方案


1

由于您正在更新订阅中的数据源,因此您应该使用它 ChangeDetectorRef 来更新视图。

注入ChangeDetectorRef到构造函数中。

constructor(private cd: ChangeDetectorRef)

并在里面.subscribe()添加:

this.cd.markForCheck()

2

在你的.html文件中

<table mat-table [dataSource]="dataSource | async">

在你的.ts文件中

 getComplaints():Observable<Item[]{
  this.dataSource = this.handler.getMyComplaints().pipe(debounceTime(20), delay(20));
  }

推荐阅读