angular - 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>
解决方案
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));
}
推荐阅读
- admob - Capacitor v3 AdMob 插件
- java - Java:为什么将一个表达式传递给 System.out.print,结果是浮点数打印 0?
- r - R Studio,TS:将函数应用于每行中的系数以生成输出向量
- scala - 在 Scala 中映射“WeightedTree”
- qt - 如何在 qt 状态机中使用 QHistoryState 来识别发生转换的最后一个状态
- algorithm - 找到向量组合以接近目标向量
- ruby - YARD 如何记录数组的@param
类型也可以是空白数组? - c++ - 代码突然结束-1073741819(0xC0000005)
- firebase - 导出后缺少 Firestore 集合
- javascript - 反应中的奇怪错误-使用阿波罗/客户端-graphql