如何在 Observable.forkJoin(...) 中捕获错误? [英] How to catch error in Observable.forkJoin(...)?

查看:28
本文介绍了如何在 Observable.forkJoin(...) 中捕获错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Observable.forkJoin() 在两个 HTTP 调用完成后处理响应,但如果其中任何一个返回错误,我如何捕获该错误?

I use Observable.forkJoin() to handle the response after both HTTP calls finishes, but if either one of them returns an error, how can I catch that error?

Observable.forkJoin(
  this.http.post<any[]>(URL, jsonBody1, postJson) .map((res) => res),
  this.http.post<any[]>(URL, jsonBody2, postJson) .map((res) => res)
)
.subscribe(res => this.handleResponse(res))

推荐答案

您可以catch 传递给 forkJoin 的每个 observable 中的错误:

You may catch the error in each of your observables that are being passed to forkJoin:

// Imports that support chaining of operators in older versions of RxJS
import {Observable} from 'rxjs/Observable';
import {forkJoin} from 'rxjs/add/observable/forkJoin';
import {of} from 'rxjs/add/observable/of';
import {map} from 'rxjs/add/operator/map';
import {catch} from 'rxjs/add/operator/catch';

// Code with chaining operators in older versions of RxJS
Observable.forkJoin(
  this.http.post<any[]>(URL, jsonBody1, postJson) .map((res) => res)).catch(e => Observable.of('Oops!')),
  this.http.post<any[]>(URL, jsonBody2, postJson) .map((res) => res)).catch(e => Observable.of('Oops!'))
)
.subscribe(res => this.handleResponse(res))

还要注意,如果你使用RxJS6,你需要用catchError代替catch,用pipe操作代替链接.>

Also note that if you use RxJS6, you need to use catchError instead of catch, and pipe operators instead of chaining.

// Imports in RxJS6
import {forkJoin, of} from 'rxjs';
import {map, catchError} from 'rxjs/operators';

// Code with pipeable operators in RxJS6
forkJoin(
  this.http.post<any[]>(URL, jsonBody1, postJson) .pipe(map((res) => res), catchError(e => of('Oops!'))),
  this.http.post<any[]>(URL, jsonBody2, postJson) .pipe(map((res) => res), catchError(e => of('Oops!')))
)
  .subscribe(res => this.handleResponse(res))

这篇关于如何在 Observable.forkJoin(...) 中捕获错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆