我有一个函数需要从 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;
});
}
this.fetchDocument(id)
返回类型为 TreeNodeDocument
的可观察对象。
只要所有文件都可以解析,这个功能就有效。现在有时会发生某些文档无法解析的情况,然后相应的 fetchDocument(id)
observable 将失败。没关系,有些文件无法解决。但是,如果其中一个失败,Observable.combineLatest
将完全失败(我知道这是一个很好的默认行为)。
我现在的问题是,我能否以某种方式使用 combineLatest
,以便只获取提取成功的文档,而忽略失败的文档?或者我可以通过不同的方式实现这一目标吗?
干杯
最佳答案
您可以将每个源 Observable(每个 this.fetchDocument(id)
)与 catchError
进行管道传输,这将用虚拟对象替换 error
通知下一个
项(或任何你想要的)。
for (let id of documentIds){
observables.push(this.fetchDocument(id).pipe(
catchError(() => of(null)),
));
}
...
请注意,您不能只使用 empty()
或 of()
因为它们都不会发出任何 next
item 和 combineLatest
不会像您期望的那样工作。当然,您可以使用任何您想要的东西来代替 null
。文档数组将在源 Observable 失败的索引处具有 null
。
关于angular - Observable.combineLatest 即使失败也会继续,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52260559/