Ich verwende Observable.forkJoin (), um die Antwort zu verarbeiten, nachdem beide http-Aufrufe beendet wurden. Wie kann ich diesen Fehler abfangen, wenn einer von beiden einen Fehler zurückgibt?
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))
Sie können den Fehler in jeder Ihrer Observablen, die an catch
übergeben werden, forkJoin
[$ var] _:
// 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))
Beachten Sie auch, dass Sie bei Verwendung von RxJS6 anstelle der Operatoren catchError
und catch
die Operatoren pipe
verwenden müssen, anstatt sie zu verketten.
// 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))
Das funktioniert bei mir:
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))
Der zweite HTTP-Aufruf wird normal aufgerufen, auch wenn beim ersten Aufruf ein Fehler auftritt