Handling 401s globally with Angular

后端 未结 8 966
误落风尘
误落风尘 2020-11-28 18:50

In my Angular 2 project I make API calls from services that return an Observable. The calling code then subscribes to this observable. For example:

getCampai         


        
8条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-28 19:28

    As frontend APIs expire faster than milk, with Angular 6+ and RxJS 5.5+, you need to use pipe:

    import { HttpInterceptor, HttpEvent, HttpRequest, HttpHandler, HttpErrorResponse } from '@angular/common/http';
    import { Observable, throwError } from 'rxjs';
    import { Injectable } from '@angular/core';
    import { catchError } from 'rxjs/operators';
    import { Router } from '@angular/router';
    
    @Injectable()
    export class AuthInterceptor implements HttpInterceptor {
    
      constructor(private router: Router) { }
    
      intercept(req: HttpRequest, next: HttpHandler): Observable> {
        return next.handle(req).pipe(
          catchError((err: HttpErrorResponse) => {
            if (err.status === 401) {
              this.router.navigate(['login'], { queryParams: { returnUrl: req.url } });
            }
            return throwError(err);
          })
        );
      }
    }
    

    Update for Angular 7+ and rxjs 6+

    import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor, HttpErrorResponse } from '@angular/common/http';
    import { Observable, of } from 'rxjs';
    import { Injectable } from '@angular/core';
    import { catchError } from 'rxjs/internal/operators';
    import { Router } from '@angular/router';
    
    @Injectable()
    export class AuthInterceptor implements HttpInterceptor {
    
      constructor(private router: Router) { }
    
      intercept(request: HttpRequest, next: HttpHandler): Observable> {
        return next.handle(request)
          .pipe(
            catchError((err, caught: Observable>) => {
              if (err instanceof HttpErrorResponse && err.status == 401) {
                this.router.navigate(['login'], { queryParams: { returnUrl: request.url } });
                return of(err as any);
              }
              throw err;
            })
          );
      }
    }
    
    

提交回复
热议问题