How to cancel current request in interceptor - Angular 4
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);}
Inspired by @RVP answer I have found out that it's possible to cut the chain with an error in the same simple way using Observable.throw()
//...intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { if (stopThisRequestWithError) { return Observable.throw('Error message'); } else { return next.handle(req); }}
This avoids fulfilling response promises with undefined values.
This is just a slight variant of RVP's answer
import { NEVER } from 'rxjs';intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { if (stopThisRequest) { return NEVER; } return next.handle(request);}
I used NEVER
instead of EMPTY
to avoid dealing with undefined values in my subscriptions (or promises).
Use NEVER
if you don't want your subscription callback to be invoked