Search code examples
angularangular-http-interceptors

How to cancel current request in interceptor - Angular 4


As you know it's possible to use Interceptors in new versions of Angular 4.

In mine, I want to cancel a request in interceptor in some conditions. So is it possible? Maybe what I should ask is: which way I should do that?

It'll also be OK if I find a way to rewrite some response to the request instead of canceling it.


Solution

  • I think all you have to do to cut the interceptor chain is to simply return an empty Observable like so:

    import { EMPTY } from 'rxjs';
    
    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
      if (stopThisRequest) {
        return EMPTY;
      }
    
      return next.handle(request);
    }