【问题标题】:return value from angularfire database list subscribe从 angularfire 数据库列表订阅返回值
【发布时间】:2018-08-14 13:53:57
【问题描述】:

我正在尝试在我的“费用”列表中汇总每笔交易的“金额”值。

这是我的数据库:

订阅中的日志有效且总计 1700,但我无法从函数中获取“this.expenseListTotal”的值以将其显示在另一个组件中。如何返回 'this.expenseListTotal' 值以便在另一个组件中使用它?

getExpenseListTotals(budgetId: string) {    
 this.afd.list('users/' + this.cUser.uid + '/budgets/' + budgetId + '/expenses').subscribe(_data => {       
   this.expenseListTotal = _data.reduce((sum, item) =>sum+item.amount,0);
  console.log("expennse list total = ",this.expenseListTotal, typeof this.expenseListTotal);
 });
}

【问题讨论】:

  • 你在控制台里得到了什么?有什么错误还是什么都没有??
  • 它正在记录“1700”值,这是两个事务的总和
  • 然后在console.log()后面加上return this.expenseListTotal;;
  • 我试过了。那行不通。我想出了下面的解决方案。谢谢!

标签: javascript angular firebase firebase-realtime-database


【解决方案1】:

服务中:

getExpenseListTotals(budgetId: string) {

return new Promise(resolve => {
  this.total = this.afd.list('users/' + this.cUser.uid + '/budgets/' + budgetId + '/expenses').subscribe((_data) => {


    this.expenseListTotal =  _data.reduce((sum, item) =>sum+item.amount,0);
    resolve(this.expenseListTotal);


  });

  })
}

在组件中:

this.total = this.budgetService.getExpenseListTotals(this.budgetId);
this.total.then(function(value){
 console.log(value)
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-09
    • 2016-07-20
    • 1970-01-01
    • 2018-07-30
    • 2018-09-04
    • 2017-07-14
    相关资源
    最近更新 更多