【问题标题】:MatTable isn't populating data from ObservableMatTable 没有从 Observable 填充数据
【发布时间】:2020-03-30 11:32:22
【问题描述】:

我正在使用 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 在以下link 中提出。

编辑: 这是 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>

【问题讨论】:

  • 我不熟悉Angularfire,但可以肯定的是,我可以看到您的代码存在一些问题。您在填充数据之前返回数据(您应该等待它)。您使用的是function 而不是arrow-functions,如果您需要this,它可能会出现问题。查看sub-collection 的文档,看看是否有帮助。

标签: angular angular-material angularfire2


【解决方案1】:

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));
  }

【讨论】:

  • 在 dataSource 参数上执行管道异步函数时出现以下错误:“MatTableDataSource”类型的参数不可分配给“Promise”类型的参数。我以前也试过。此外,当您像上面那样分配 this.dataSource 时,它​​会返回一个 Observable;它应该为 mat-table 数据源输入属性返回一个 MatTableDataSource 引用。 ChangeDetectorRef 也不能正常工作。
【解决方案2】:

我通过删除 debounceTime 运算符并将延迟运算符间隔从 20 毫秒增加到 1000 毫秒来使其工作。根据我的观察,客户端 MatTable 组件在接收异步数据之前需要更多时间来渲染。组件类现在看起来像这样:

 ngOnInit() {
    this.getComplaints();
  }

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

感谢您帮助我 @alin0509 和 @developer033

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-19
    • 2020-01-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多