我试图获取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"
category.forEach()
循环似乎没有被执行。