[英]How to push a list to Firebase Realtime Database
我正在 Ionic 3 上開發移動應用程序。我在 firebase 數據庫上有一個通知對象。 我正在以這種方式推送一條記錄的數據:
fireNots = firebase.database().ref('/notifications');
addNotification(notReq: INotReq){
this.fireNots.child(notReq.RecipientUId).push({
Title: notReq.Title,
Body: notReq.Body
}).then(() => {
resolve({ success: true });
})
}
這是 INotReq:
export interface INotReq{
RecipientUId: string,
Title: string,
Body: string
}
我在 Firebase 上的數據結構:
- 通知
- Q6cQqz0OVRPCq17OWb (RecipientUId)
- LtH7QZlWVUcIpNqb-O9
- 正文:“你有一個通知。”
- 標題:“通知標題”
現在我需要推送通知列表 (notReqs: INotReq[])。
我應該像這樣使用for循環嗎?
addMultipleNotification(notificationRequestArray: INotReq[]){
notificationRequestArray.forEach(notificationRequest => {
this.addNotification(notificationRequest);
});
}
這會是一種不好的做法嗎? 或者有更好的方法嗎?
你有(至少)另外兩種可能性:
使用update()
方法一次將多個值寫入數據庫。 另見此處。
addMultipleNotification(notificationRequestArray: INotReq[]){ const fireNots = firebase.database().ref('/notifications'); var updates = {}; notificationRequestArray.forEach(notificationRequest => { var newKey = fireNots.child(notificationRequest.RecipientUId).push().key; updates['/notifications/' + newKey] = { Title: notificationRequest.Title, Body: notificationRequest.Body }; }); return firebase.database().ref().update(updates).then(() => {...}) }
使用將並行運行所有異步push()
操作的Promise.all()
並“返回一個承諾,當所有作為可迭代傳遞的承諾都已實現時,該承諾將實現”:
addMultipleNotification(notificationRequestArray: INotReq[]){ const fireNots = firebase.database().ref('/notifications'); var promises = []; notificationRequestArray.forEach(notificationRequest => { promises[fireNots.child(notificationRequest.RecipientUId).push({ Title: notificationRequest.Title, Body: notificationRequest.Body })] }); return Promise.all(promises).then(() => {...}) }
請注意,這兩種方法之間存在重要區別:
通過使用update()
,同步更新是原子的:要么所有更新都成功,要么所有更新都失敗。
另一方面,如果您使用Promise.all()
一些推送可能會失敗(例如,特定節點的安全規則會阻止寫入)但其他推送會成功。
另外,請注意,這兩種方法的優點是您確切知道何時完成對數據庫的所有寫入,因此您可以在.then(() => {...})
方法中做任何您想做的事情(通知最終用戶,重定向到另一個頁面等)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.