如何正确订阅更改? -Angularfire2 [英] How do I properly subscribe to changes? -Angularfire2

查看:91
本文介绍了如何正确订阅更改? -Angularfire2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我没有经常使用Firebase。我用来获取值的方法感觉很乱......



我正在使用这种方法来获取每个object.value的总和金额一个ListObservable



谁能说出订阅更改的最佳方式是什么,以便totalAmount保持最新状态?



Hello, I haven't used Firebase a lot. The method I'm using to get values feels messy...

I'm using this method to get the sum amount for each object.value in a ListObservable

Can anyone tell what would be the best way to subscribe to changes such that the totalAmount stays up to date?

//Returns a promise of the total sum for each object.amount under a category
getTotalAmountPromise(observable) {
  let totalAmount: number = 0;
  return new Promise(function(resolve, reject) {
    let count = 0;

    observable.$ref.ref.on('child_added', childs => {
      childs.ref.once('value', obj => {
        totalAmount += obj.val().amount;
        count++;

        let length = childs.numChildren();
        if(count == length) {
          resolve(totalAmount);
        }
      });
      setTimeout(() => {
        if (!(count == length))
          reject(Error('Data rejected. Count: ' + count + ', Childs: ' + length));

      }, 5000);
    });

  });
}





我尝试过:



我似乎无法找到一个好办法。希望这里有人可以提供一些指导。



What I have tried:

I can't seem to find a good way to do this. Was hoping anyone here could come with some guidance.

推荐答案

ref.ref.on(' child_added',childs => {
childs.ref.once(' value',obj => {
totalAmount + = obj.val()。amount;
count ++;

length = childs.numChildren();
if (count == length){
resolve (totalAmount);
}
});
setTimeout(()=> {
if (!( count == length))
reject(错误(' 数据被拒绝。计数:' + count + ' ,Childs:' + length));

}, 5000 );
});

});
}
ref.ref.on('child_added', childs => { childs.ref.once('value', obj => { totalAmount += obj.val().amount; count++; let length = childs.numChildren(); if(count == length) { resolve(totalAmount); } }); setTimeout(() => { if (!(count == length)) reject(Error('Data rejected. Count: ' + count + ', Childs: ' + length)); }, 5000); }); }); }





我尝试过:



我似乎无法找到一个好办法。希望这里有人可以提供一些指导。



What I have tried:

I can't seem to find a good way to do this. Was hoping anyone here could come with some guidance.


这篇关于如何正确订阅更改? -Angularfire2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆