Click here to Skip to main content
15,883,938 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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?

JavaScript
//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.
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900