Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 692
Behnam Azimi Avatar asked Sep 26 '17 19:09

Behnam Azimi


People also ask

What is Http_interceptors in angular?

HTTP_INTERCEPTORSlinkA multi-provider token that represents the array of registered HttpInterceptor objects.

Can we have more than 1 interceptor in angular?

After providing HTTP_INTERCEPTORS we need to inform the class we are going to implement our interceptor into by using useClass. Setting multi to true, makes sure that you can have multiple interceptors in your project.


2 Answers

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.

like image 29
veritas Avatar answered Sep 18 '22 20:09

veritas


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); } 
like image 165
RVP Avatar answered Sep 17 '22 20:09

RVP