【问题标题】:How to catch all different responses from an array of observables?如何从一组可观察对象中捕获所有不同的响应?
【发布时间】:2019-11-20 11:33:45
【问题描述】:
在 Angular 中,我有一组可观察对象。我想执行所有这些 observables,但也要处理所有不同的结果。当我尝试使用forkJoin 或combineLatest 来实现这一点时,我只在测试场景中得到一个(错误)响应,其中我有4 个都失败的可观察对象。
例子:
const callsToExecute = [];
vehicles.forEach(vehicle => {
callsToExecute.push(this.createRequest(vehicle.id));
)};
forkJoin(callsToExecute).subscribe(result => {}, error => {/** single response error */});
如何捕捉所有不同的响应?
【问题讨论】:
标签:
angular
rxjs
observable
【解决方案1】:
您可以尝试以下方法来捕获单个可观察对象的错误:
const callsToExecute = [];
callsToExecute.push(of('Hello').pipe(map((res) => res), catchError(e => of('Oops! 1'))));
callsToExecute.push(of('Hello 2').pipe(map((res) => res), catchError(e => of('Oops! 2'))));
callsToExecute.push(of('Hello 3').pipe(map((res) => res), catchError(e => of('Oops! 3'))));
const example = forkJoin(
callsToExecute
);
const subscribe = example.subscribe(val => console.log(val));
我已经创建了 stackBlitz 示例 Example1 Example2