【问题标题】:How to push a list to Firebase Realtime Database如何将列表推送到 Firebase 实时数据库
【发布时间】:2020-03-25 16:32:17
【问题描述】:

我正在 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);
    });
  }

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

【问题讨论】:

    标签: typescript firebase firebase-realtime-database ionic3


    【解决方案1】:

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

    1. 使用update() 方法一次将多个值写入数据库。另见here

      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. 使用 Promise.all() 将并行运行所有异步 push() 操作并“返回一个单一的 Promise,当所有作为迭代传递的承诺都已履行时履行”:

      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(() => {...}) 方法中做任何您想做的事情(通知最终用户,重定向到另一个页面等)。

    【讨论】:

      猜你喜欢
      • 2021-08-28
      • 2021-10-07
      • 1970-01-01
      • 2018-04-08
      • 2019-09-20
      • 1970-01-01
      • 1970-01-01
      • 2018-05-03
      • 2020-01-12
      相关资源
      最近更新 更多