即使失败,Observable.combineLatest 也会继续

Tom*_*Tom 7 rxjs typescript angular

我有一个功能需要从 firebase 解析多个文档

  fetchDocuments(documentIds: string[]): Observable<TreeNodeDocument[]> {
    const observables = [];
    for(let id of documentIds){
      observables.push(this.fetchDocument(id));
    }
    return Observable.combineLatest(observables, (...docs: TreeNodeDocument[]) => {
      //some transformations on the resolved documents
      return docs;
    });
  }
Run Code Online (Sandbox Code Playgroud)

this.fetchDocument(id)返回一个 observable 类型TreeNodeDocument

只要可以解析所有文档,此功能就起作用。现在有时会发生某些文档无法解析的情况,那么相应的 fetchDocument(id)observable 就会失败。可以,预计某些文件无法解析。但是,Observable.combineLatest如果其中一个失败,则完全失败(我知道这是一个很好的默认行为)。

我现在的问题是,我可以combineLatest以某种方式使用,以便我只获取获取有效的文档,而忽略获取失败的文档吗?或者我可以以不同的方式实现这一目标?

干杯

mar*_*tin 8

您可以通过管道将每个源 Observable (each this.fetchDocument(id))catchError替换为error一个虚拟next项目(或任何您想要的)。

for (let id of documentIds){
  observables.push(this.fetchDocument(id).pipe(
    catchError(() => of(null)),
  ));
}

...
Run Code Online (Sandbox Code Playgroud)

请注意,您不能仅使用empty()of()因为它们都不会发出任何next项目并且combineLatest无法按预期工作。当然,null你可以使用任何你想要的东西来代替。文档数组将具有null源 Observable 失败的索引。