【问题标题】:Firebase - child_added being called on delete of itemFirebase - 在删除项目时调用 child_added
【发布时间】:2018-06-20 21:16:08
【问题描述】:

我有一个post 的列表,我正在使用.on('child_added') 获取它们,问题是我只想在添加项目时获得post而不是当它被删除,然而,似乎.on('child_added') 被调用,即使是在一个帖子被删除时。这不是我需要的。

这是我的功能:

if(fromClick) { this.subscription.off(); this.firstRun = true;}
this.postFeed = new Array();
this.subscription = this.database.database.ref('/posts/'+this.locationId)
   .orderByChild('created')
   .limitToLast(10);

this.subscription.on('child_added', (snapshot) => {
   this.postFeed.push(snapshot.val());
});

所以它显示最后一个10,然后当添加一个项目时,它也会将其添加到数组中,但是当一个项目被删除时,它会再次被调用..

如何防止这种情况发生?这样调用只发生在添加的post 上?

【问题讨论】:

    标签: javascript angular firebase firebase-realtime-database


    【解决方案1】:

    如果你打电话:

    this.database.database.ref('/posts/'+this.locationId)
       .orderByChild('created')
       .limitToLast(10);
    

    您正在创建一个包含 10 个最新帖子的查询。如果您删除其中一个,另一个将成为第 10 个最近的帖子,因此您会为此获得 child_added

    我能想象的唯一一件事就是只得到 10 一次,然后做一个limitToLast(1)

    this.database.database.ref('/posts/'+this.locationId)
       .orderByChild('created')
       .limitToLast(10)
       .once("value", function(snapshot) {
         snapshot.forEach(function(child) {       
           // These are the initial 10 children
         });
       });
    this.database.database.ref('/posts/'+this.locationId)
       .orderByChild('created')
       .limitToLast(1)
       .on("child_added", function(snapshot) {
         // This is the latest child, but this will also fire when you remove the current latest
       });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-12
      • 1970-01-01
      • 1970-01-01
      • 2018-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-02
      相关资源
      最近更新 更多