I have a Firebase Realtime Database containing the following:
"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"
}
I simplified it but it has a similar structure to this. I am trying to list in a mat-table the Receipts with a given store_id using a query from AngularFireDatabase equalTo("given store_id") in a MatTable in Angular, but I do not want to show the user_id in the table, I want to show the user_name that I can get by querying "user" with a user_id to get the name.
I am doing something like this:
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
})
In the .html, everything in the dataSource shows correctly but the user_name
, which is undefined. If i console.log(user_name)
inside the second subscription, it shows correctly. But I see the console.log(user_name)
inside the second subscription executes after the object "receipt" I create is pushed into the tempArray
, therefore it is undefined when it gets pushed into the array.
The methods in the storeService I use look like this:
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;
}))
}
I do not think mergeMap is working here, I've tried it and I had no success with it. Any ideas on what approach I should have in order to not show user_id in the table, but the user_name provided by the query?