angular HttpClient 拦截器 拦截401请求重定向

  • 参考地址: https://semlinker.com/ng-http-interceptor/

  • 实现(request.service)

    import { Injectable } from "@angular/core";
    import { Observable, of, throwError } from "rxjs";
    import { catchError, map, tap } from "rxjs/operators";
    import {
      HttpHeaders,
      HttpClient,
      HttpRequest,
      HttpHandler,
      HttpErrorResponse,
      HttpEvent,
      HttpResponse,
      HttpInterceptor,
    } from "@angular/common/http";
    import Config from "../../config/index";
    
    @Injectable({
      providedIn: "root",
    })
    export class RequestService implements HttpInterceptor {
      constructor(private http: HttpClient) {}
    
      /**
       * 错误消息类
       * @param error
       */
      private handleError(error: HttpErrorResponse) {
        console.log(error, "res112212");
        if (error.error instanceof ErrorEvent) {
          console.error("An error occurred:", error.error.message);
        } else {
          console.error(
            `Backend returned code ${error.status}, ` + `body was: ${error.error}`
          );
        }
        return throwError("Something bad happened; please try again later.");
      }
    
      intercept(
        request: HttpRequest<any>,
        next: HttpHandler
      ): Observable<HttpEvent<any>> {
        return next.handle(request).pipe(
          map((event: HttpEvent<any>) => {
            if (event instanceof HttpResponse) {
              console.log(event.body.code, "code");
              switch (event.body.code) {
                case 200:
                  break;
                case 401:
                  localStorage.removeItem("token");
                  window.location.href = "/login";
                  break;
                case 500:
                  // this.OpenMessage('提示', '数据错误500')
                  break;
              }
            }
            return event;
          })
        );
      }
    }
    
    
  • app.module.ts

  providers: [
    // 添加
    { provide: HTTP_INTERCEPTORS, useClass: RequestService, multi: true },
  ],
©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页