mat*_*ang 15 promise rxjs angular-http angular angular-httpclient
两个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))
Run Code Online (Sandbox Code Playgroud)
siv*_*636 25
您可能会catch
传递到每个可观察对象中的错误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))
Run Code Online (Sandbox Code Playgroud)
还要注意的是,如果你使用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, 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))
Run Code Online (Sandbox Code Playgroud)
Was*_*aga 11
这对我有用:
forkJoin(
this.http.post<any[]>(URL, jsonBody1, postJson).pipe(catchError(error => of(error))),
this.http.post<any[]>(URL, jsonBody2, postJson)
)
.subscribe(res => this.handleResponse(res))
Run Code Online (Sandbox Code Playgroud)
第二次 HTTP 调用会正常调用,即使第一次调用出错
归档时间: |
|
查看次数: |
12734 次 |
最近记录: |