我的array.forEach循环没有被执行

时间:2016-11-26 16:32:46

标签: javascript typescript firebase angularfire2

我试图获取firebase中某个类别下每个object.amount的总金额。

/* Returns a Firebase list object as an array */
  getListAsArray(path: string): Array<any> {
    let arr = new Array<any>();
    this.af.database.list(path).$ref.on("child_added", childs => { 
      childs.ref.orderByChild
      childs.ref.once("value", obj => {
        let object = obj.val();
        object.$key = obj.key;
        arr.push(object);
      });
    });
    return arr;                                                       //Works fine
  }

  //Returns the total sum for each object.amount under a category
  getTotalAmount(path: string){
    let category: any[] = this.fbp.getListAsArray(path);
    let totalAmount: number = 0;

    category.forEach( category => {
      totalAmount += category.amount;
      console.log(totalAmount);                                    //Does not print
      console.log("test");                                         //Does not print
    });

    console.log(category);              //Printes the array with every object as expected.
    return totalAmount;                 //Always returns 0
  }


/* In a constructor */
let totalAmountFood = cp.getTotalAmount('/expense/food');
console.log(totalAmountFood);                                       //Prints "0"
  1. 从firebase获取列表对象将返回预期值
  2. category.forEach()循环似乎没有被执行。

0 个答案:

没有答案