angular http请求封装(带token)

1,创建一个ts文件;

2,base-interceptor.ts;写入代码:

import { Injectable } from '@angular/core';
import { Router,ActivatedRoute } from '@angular/router';
import {
  HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpErrorResponse
} from "@angular/common/http";
import { PublicService } from "../public/public.service";
import { throwError } from 'rxjs';
import { catchError, retry } from "rxjs/operators";
import * as Cookies from 'js-cookie';
@Injectable()
export class BaseInterceptor implements HttpInterceptor {
  public erors;
  constructor(public router: Router, public url: PublicService) {}
  intercept(req, next: HttpHandler) {
    let hadBaseurl = Boolean(req.headers.get('hadBaseurl')) || false;
    let newReq = req.clone({
      url: hadBaseurl ? `${req.url}` : `${baseurl}${req.url}`,
    });
    let Cookie = Cookies.get('manageAuthorizationData');
    if (!req.cancelToken) {
      newReq.headers =
        newReq.headers.set('Authorization', 'Bearer '+Cookie);
    }
    return next.handle(newReq)
      .pipe(
        retry(2),
        catchError(this.handleError)
      );
  }
  private handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
      console.error('An error occurred:', error.error.message);
    } else {
      /*console.log(error);*/
      this.erors = error;
      if (this.erors.error.Message == '已拒绝为此请求授权。') {
        localStorage.setItem('quan', 'true');
        window.location.href = '#/Login';
      }
      console.error(
        `Backend returned code ${error.status}, ` +
        `body was: ${error.error}`);
    }
    // return an observable with a user-facing error message
    return throwError(
      'Something bad happened; please try again later.');
  };
}
3,index.ts中引入base-interceptor.ts;
import { HTTP_INTERCEPTORS } from '@angular/common/http';

import { BaseInterceptor } from './base-interceptor';

/** Http interceptor providers in outside-in order */
export const httpInterceptorProviders = [
  { provide: HTTP_INTERCEPTORS, useClass: BaseInterceptor, multi: true },

];

2,在app.module.ts引入,都可以用了;

 

 

posted @ 2020-04-29 14:40  到货  阅读(2079)  评论(0编辑  收藏  举报