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

时间:2019-11-30 11:13:17

标签: typescript firebase firebase-realtime-database ionic3

我正在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 个答案:

答案 0 :(得分: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()操作,并“返回在兑现作为可迭代对象传递的所有诺言时都实现的一个诺言”: >

    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(() => {...})方法中执行所需的任何操作(通知最终用户,重定向到另一个页面,等等。)