liqSTAR
liqSTAR

Reputation: 1305

Make an http request inside error handling Angular 7 RXJS

Hi catched the error internal server error already and logged em. But I dont know how to call the next request inside this error handling. I need to revert the beginning selectElevation(elevation.id) request by calling another request method selectPhase(this.sessionState.phaseId) if the request selectElementPricelistConfigurator() fails.

goToConfiguratorAndLoadData(elevation: Elevation) {
        this.apiService.selectElevation(elevation.id).pipe(
            mergeMap( () => this.apiService.selectElementPricelistConfigurator() ),
        ).subscribe(
        (next) => {
            ...
        },
        (err: Error | HttpErrorResponse) => {
            if (err instanceof HttpErrorResponse) {
                if (err.status === 500) {
                    console.log('Error', err.status);
                    this.apiService.selectPhase(this.sessionState.phaseId);
                }
            } else {
                throwError(err);
            }
        }
    );
}

The server just stops and is not firing this http request. enter image description here

Thanks for any help, didnt found any similiar problem.

Edited:

ApiServer - selectPhase Method:

selectPhase(phaseId: string): Observable<any> {
    return this.httpClient.post(this.apiUrl + '/phases/select', {
        identifier: phaseId,
    });
}

Upvotes: 1

Views: 461

Answers (2)

this.apiService.selectPhase(this.sessionState.phaseId) request is not called because there is no .subscribe() on it (assuming it returns an observable). Although, this is not the good way to do it, the good way is using the operator catchError in order to modify the error and perform some custom actions.

With catchError, you don't need to 'subscribe()' to the observable, catcError will flat the observable that you return on it's callback function.

Example:

goToConfiguratorAndLoadData(elevation: Elevation) {
        this.apiService.selectElevation(elevation.id).pipe(
            mergeMap( () => this.apiService.selectElementPricelistConfigurator() ),
            catchError((err: Error | HttpErrorResponse) => {
                if (err instanceof HttpErrorResponse && err.status === 500) {
                    console.log('Error', err.status);
                    return this.apiService.selectPhase(this.sessionState.phaseId);
                } else {
                   return throwError(err);
                }
            })
        ).subscribe(
        (next) => {
            ...
        }

    );
}

Hope this helps!

Upvotes: 1

Julien Breem
Julien Breem

Reputation: 113

Assuming that

this.apiService.selectPhase(this.sessionState.phaseId)

return a RxJS Observable, you need to subscribe to it for the request to fire.

To quote the official doc:

To invoke the Observable and see these values, we need to subscribe to it:

Upvotes: 1

Related Questions