有一個包含檔案的父集合tables,每個檔案都有一個名為 的集合orders。我想訂閱表格并收聽訂單更改。我嘗試了什么:
在我的餐桌服務
watchTables(): Observable<any> {
return this.afStore
.collection('restaurants')
.doc(this.rid)
.collection('tables')
.snapshotChanges()
.pipe(
map((data: any) =>
data.map((documentDataTable: any) => ({
id: documentDataTable.payload.doc.id,
...documentDataTable.payload.doc.data()
}))
.sort((a: any, b: any) => a.number - b.number)
),
mergeMap((tables: any) => this.ordersService.watchOrders(tables))
);
}
在我的訂單服務
watchOrders(tables: any): Observable<any> {
let orders$: Observable<any>[] = [];
tables.forEach((table: any) =>
orders$.push(
this.afStore
.collection('restaurants')
.doc(this.rid)
.collection('tables')
.doc(table.id)
.collection('orders')
.snapshotChanges()
.pipe(
map((data: any) => {
return data.map((documentDataOrder: any) => ({
id: documentDataOrder.payload.doc.id,
...documentDataOrder.payload.doc.data()
}))
.sort((a: any, b: any) => this.sortOrders(a, b))
})
).pipe(
map(data => ({ table: table, orders: data }))
)
));
return zip(orders$);
}
在我的組件中使用表服務
subscribeToTables() {
this.tablesService
.watchTables()
.subscribe((collectedTablesData: any) => {
console.log('table or orders changed');
});
}
我想解構資料,但我自己找不到答案。或者我只是在搞亂 Observables,可能兩者兼而有之。
我在解決方案中需要的東西:
- 我
orders在獲取資料的同時需要tables資料(這就是為什么首先我認為訂單將作為地圖陣列的一部分作為表格檔案的一部分,但這不是矯枉過正嗎?) - 我需要知道我的表組件的訂單何時更改,因為包含行擴展資料表,資料表中的
table狀態取決于orders狀態。
uj5u.com熱心網友回復:
正如您似乎已經收集到的那樣,沒有辦法同時收聽父檔案及其子集合。Firestore 中的讀取和偵聽是淺層的,并且只覆寫一個集合或具有特定名稱的所有集合。
你有幾個選擇:
您可以在表格檔案中包含一個欄位來指示其訂單的狀態。在最簡單的情況下,這可能是一個
ordersLastUpdatedAt時間戳欄位,但您也可以擁有一個訂單 ID 串列以及它們各自最近更新的時間戳。無論哪種方式,您都應該在更新相關訂單時更新表格檔案中的欄位,然后將其用作客戶端中的觸發器以(重新)加載表格的訂單。您還可以在表格檔案的路徑上使用集合組查詢
orders,正如 Sam 在他對 CollectionGroupQuery 的回答中所展示的那樣,但將搜索限制為特定檔案下的子集合。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/489333.html
