【发布时间】:2021-08-15 05:43:21
【问题描述】:
我有一个 Firebase 实时数据库,其中包含以下内容:
"user":
1: {
"id": 1,
"name": "Jason"
}
"receipts":
1: {
"id": 1,
"store_id": 1,
"user_id": 1,
"product": "apples"
},
2: {
"id" : 2,
"store_id": 2,
"user_id": 1,
"product": "oranges"
}
我对其进行了简化,但它的结构与此类似。我正在尝试在 Angular 的 MatTable 中使用来自 AngularFireDatabase equalTo("given store_id") 的查询,在 mat-table 中列出具有给定 store_id 的 Receipts,但我不想在表中显示 user_id,我想显示我可以通过使用 user_id 查询“user”来获取名称的 user_name。
我正在做这样的事情:
receiptDetails = new MatTableDataSource();
...
this.storeService.getReceiptsByStoreId(store_id).subscribe(result => {
let tempArray:any = []
result.forEach((element) => {
let object:any = element.payload.val()
let user_name:any;
this.storeService.getUserNameByUserId(object.user_id).subscribe(result => user_name = result)
let receipt:any = {
id: object.id,
product: object.product,
user_id: user_name
}
tempArray.push(receipt)
});
this.receiptDetails.data = tempArray
})
在 .html 中,dataSource 中的所有内容都正确显示,但 user_name 未定义。如果我在第二个订阅中console.log(user_name),它会正确显示。但是我看到第二个订阅中的console.log(user_name) 在我创建的对象“receipt”被推入tempArray 之后执行,因此当它被推入数组时它是未定义的。
我使用的 storeService 中的方法是这样的:
public getReceiptsByStoreId(store_id: number) {
return this.db.list('/receipts', ref => ref.orderByChild('store_id').equalTo(store_id)).snapshotChanges()
}
public getUserNameByUserId(user_id: number) {
return this.db.object('/user/'+ user_id).snapshotChanges().pipe(map(user=>{
let object:any=user.payload.val();
let name=object.name;
return name;
}))
}
我认为mergeMap 在这里不起作用,我已经尝试过了,但没有成功。关于我应该采用什么方法以便不在表中显示 user_id 而是查询提供的 user_name 的任何想法?
【问题讨论】:
-
@Eliseo 非常感谢您的回答。不幸的是,我调整了我项目的所有答案都无济于事,他们都没有得到任何数据供我在表格中显示。
-
我写了一个答案。我指出的链接确实有一些不同,我希望 cmets 帮助您理解代码。注意:不要担心 rxjs 运算符。在这个例子中你最需要的是:switchMap、forkJoin 和 map(其实还有很多,但最常用的只有这三个)
标签: angular firebase firebase-realtime-database