繁体   English   中英

如何将列表推送到 Firebase 实时数据库

[英]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);
    });
  }

这会是一种不好的做法吗? 或者有更好的方法吗?

你有(至少)另外两种可能性:

  1. 使用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(() => {...}) }
  2. 使用将并行运行所有异步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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM