【问题标题】:Angular ForEach loop with Firebase call async issue带有 Firebase 调用异步问题的 Angular ForEach 循环
【发布时间】:2021-11-24 19:49:27
【问题描述】:

这是我的代码:

getTotalBookListCost(bookList:string[]):number
  {
    let cost=0;
    bookList.forEach(el=>{
      this.store.doc("Books/"+el).get().subscribe(data=>{
        let temp=<Book>data.data();
        cost+=temp.cost;
      },error=>this.toastr.error(error.message));
    });
    return cost;
  }

返回的值是 0,我猜是因为返回是在带有 firebase 调用的 forEach 循环之前执行的。如何只在循环执行后才返回?

【问题讨论】:

  • 您的 store.doc 是异步函数,您不能像这样更改为 Promise 或 Observable return 一样使用。

标签: angular typescript firebase google-cloud-firestore


【解决方案1】:

是的,函数先返回数据,然后再firebase返回数据。您可以尝试使用 combineLatest 运算符,如下所示:

getTotalBookListCost(bookList:string[]):Observable<number>
{
  let cost=0;
  return 
  combineLatest(bookList.map(el=>this.store.doc("Books/"+el).get())
  .pipe(
      map(result=> {
        const bookCosts = result.map(data => data.data().cost);
        return bookCosts.reduce(function(a, b) { return a + b; }, 0);
      })
  );
}

您需要注意,现在您的函数将返回一个 Obserbable,而不是一个数字。

编辑:正如 Andrei 所说,该函数返回 Subscription,而不是 Observable。我现在已经修复了它,所以你需要知道你需要订阅它。

【讨论】:

  • 这里订阅返回,不对
猜你喜欢
  • 2018-03-06
  • 2015-04-18
  • 2019-03-24
  • 2019-02-15
  • 2013-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-20
相关资源
最近更新 更多