查看: 23|回复: 0

angular http请求封装(带token)

[复制链接]

2

主题

0

回帖

0

积分

积极分子

金币
0
阅读权限
220
精华
0
威望
0
贡献
0
在线时间
0 小时
注册时间
2008-3-30
发表于 2020-4-29 14:40:00 | 显示全部楼层 |阅读模式

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引入,都可以用了;

 

 



来源:https://www.cnblogs.com/xianc/p/12802091.html
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

相关侵权、举报、投诉及建议等,请发 E-mail:qiongdian@foxmail.com

Powered by Discuz! X5.0 © 2001-2026 Discuz! Team.

在本版发帖返回顶部