How to cancel current request in interceptor - Angular 4

后端 未结 7 1944
情书的邮戳
情书的邮戳 2021-02-05 01:29

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 i

相关标签:
7条回答
  • 2021-02-05 01:52

    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.

    0 讨论(0)
  • 2021-02-05 01:58

    As suggested above, there is more optimal way to handle the error with custom response

    import { throwError, Observable } from 'rxjs';
    import { HttpEvent } from '@angular/common/http';
    
    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
      if (authFailedDummy(request)) {
        return throwError(new Error('Authorization error: The request did not go through'));
      }
      return next.handle(request);
    }
    
    0 讨论(0)
  • 2021-02-05 02:05

    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

    0 讨论(0)
  • 2021-02-05 02:08
    let sub = this.http.get(url, {headers: reqHeaders})
                .subscribe(
                    (res) => {
                        res = res.json();
                    }
                );
    
    sub.unsubscribe();
    
    0 讨论(0)
  • 2021-02-05 02:13

    @RVP's code will work, We can do one more thing for same.

    add return only, it will also work

        intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
              if(helper.isTokenExpired(tokenVal)){
                  return;
              }
            .
            . <{code}>
            .
    
        }
    
    0 讨论(0)
  • 2021-02-05 02:13

    To Angular 6, you need can user the following structure to return a empty Observable:

    import {Observable} from 'rxjs';
    import {empty} from 'rxjs/internal/Observer';
    
    //...
    
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        if (stopThisRequest) {
            return Observable.create(empty);
        } else {
            return next.handle(req);
        }
    }
    
    0 讨论(0)
提交回复
热议问题