angular – 如何在Observable.forkJoin(…)中捕获错误?
发布时间:2020-12-17 07:14:50 所属栏目:安全 来源:网络整理
导读:两个http调用完成后,我使用Observable.forkJoin()来处理响应,但如果其中任何一个返回错误,我怎么能捕获该错误? Observable.forkJoin( this.http.postany[](URL,jsonBody1,postJson) .map((res) = res),this.http.postany[](URL,jsonBody2,postJson) .map((r
两个http调用完成后,我使用Observable.forkJoin()来处理响应,但如果其中任何一个返回错误,我怎么能捕获该错误?
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)) 解决方法
您可能会捕获传递给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,postJson) .map((res) => res)).catch(e => Observable.of('Oops!')),postJson) .map((res) => res)).catch(e => Observable.of('Oops!')) ) .subscribe(res => this.handleResponse(res)) 另请注意,如果使用RxJS6,则需要使用catchError而不是catch和pipe运算符而不是链接. // 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,postJson) .pipe(map((res) => res),catchError(e => of('Oops!'))),catchError(e => of('Oops!'))) ) .subscribe(res => this.handleResponse(res)) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |