Handling 401s globally with Angular

后端 未结 8 980
误落风尘
误落风尘 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:32

    Angular 4.3+

    With the introduction of HttpClient came the ability to easily intercept all requests / responses. The general usage of HttpInterceptors is well documented, see the basic usage and how to provide the interceptor. Below is an example of an HttpInterceptor that can handle 401 errors.

    Updated for RxJS 6+

    import { Observable, throwError } from 'rxjs';
    import { HttpErrorResponse, HttpEvent, HttpHandler,HttpInterceptor, HttpRequest } from '@angular/common/http';
    
    import { Injectable } from '@angular/core';
    import { catchError } from 'rxjs/operators';
    
    @Injectable()
    export class ErrorInterceptor implements HttpInterceptor {
    
      intercept(req: HttpRequest, next: HttpHandler): Observable> {
        return next.handle(req).pipe(
          catchError((err: HttpErrorResponse) => {
            if (err.status == 401) {
              // Handle 401 error
            } else {
              return throwError(err);
            }
          })
        );
      }
    
    }
    

    RxJS <6

    import { Injectable } from '@angular/core';
    import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpErrorResponse } from '@angular/common/http'
    import { Observable } from 'rxjs/Observable';
    import 'rxjs/add/operator/do';
    
    @Injectable()
    export class ErrorInterceptor implements HttpInterceptor {
    
        intercept(req: HttpRequest, next: HttpHandler): Observable> {
            return next.handle(req).do(event => {}, err => {
                if (err instanceof HttpErrorResponse && err.status == 401) {
                    // handle 401 errors
                }
            });
        }
    }
    

提交回复
热议问题