Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 5 HttpInterceptor Retry Request

Tags:

angular

How can an Angluar 5 HttpInterceptor retry a request on error?

The Angular docs don't show an example of an HttpInterceptor retry: https://angular.io/guide/http https://angular.io/api/common/http/HttpInterceptor

Note that there is a retry on the HttpClient object. This is NOT helpful in this case.

Psuedo logic I'm trying to achieve: Send request IF error response THEN change the request and retry the request.

This HttpInterceptor successfully runs the request and catches the error but doesn't retry the request.

export class AuthInterceptor implements HttpInterceptor {
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        return next
            .handle(req)
            .do(event => {
            }, (err: any) => {
                let reqRepeat = req.clone(); // For now, keep it simple. Don't change original request.
                return next.handle(req); // Retry request. THIS DOESN'T SEEM TO DO ANYTHING!
            })
    }
};
like image 309
Aydus-Matthew Avatar asked Jan 19 '18 20:01

Aydus-Matthew


People also ask

Which RxJS operator can be used to retry a failed HTTP request?

In other words, we can say that the RxJS retry() operator is used to handle and take care of retrying back on the source observable if it finds there any error and then retry according to the input count given.

What is retry in angular?

ReTry & ReTryWhen Operators help us to retry a failed observable in Angular. These operators are useful in Error handling. They both resubscribe to the source observable when they receive onError() notification.

What is Httpinterceptor in angular?

What is an Angular HTTP Interceptor. The angular interceptor is a medium connecting the backend and front-end applications. Whenever a request is made, the interceptors handle it in between. They can also identify the response by performing Rxjs operators.

How do I use Httpinterceptor?

HTTP Interceptors is a special type of angular service that we can implement. It's used to apply custom logic to the central point between the client-side and server-side outgoing/incoming HTTP request and response. Keep in mind that the interceptor wants only HTTP requests.


1 Answers

The rxjs 'do' operator does not modify the observer. Returning the 'next.handle(...)' should not work.

Try to use the 'catch' operator instead.

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req).catch(() => {
      const newReq = req.clone();
      return next.handle(newReq);
    });
  }

Do not forget to import the catch operator:

import 'rxjs/add/operator/catch';
like image 148
Leandro Lima Avatar answered Sep 22 '22 12:09

Leandro Lima