I want to make a call to a server that can return an authorization fail (401) with Angular2\'s HTTP class.
The flow of the request should look like that:
I believe the solution has changed a little, since in the news versions of Angular we must use the pipe()
method. So I decided to use a custom operator solution. One good thing is the handleError()
method could be exported as a global function and then be used in more than one service.
See this solution for more details: https://blog.angularindepth.com/retry-failed-http-requests-in-angular-f5959d486294
export class MyService {
// ...
public getSomething(): Observable {
return this.http.get(url, options).pipe(this.handleError('Maybe your a custom message here'));
}
private handleError(errorMessage: string) {
return (source: Observable) => source.pipe(
retryWhen(errors => errors.pipe(
mergeMap((errorResponse: HttpErrorResponse) => {
console.error(errorMessage);
if (errorResponse.status === 401) {
const closedSubject = new Subject();
this.modalService.open(new ModalConfig({
content: LoginModalComponent,
close: () => {
closedSubject.next();
}
}));
return closedSubject;
}
return throwError(errorResponse);
})
))
);
}
}