angularcli 拦截器封装

新建一个service.ts

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpEvent, HttpHandler, HttpRequest, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
const ignoreToken = ['adminlogin','getcaptchaimg',"userlogin"];//不需要传token路由
import { NzMessageService } from 'ng-zorro-antd/message';
import { Router } from '@angular/router';
@Injectable()
export class CommonInterceptor implements HttpInterceptor {
    constructor(
        private msg:NzMessageService,
        private router: Router,
    ) {

    }
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // 先补全请求协议
    let url = req.url;
    const needToken = ignoreToken.filter(u => url.match(u));
    if (url.indexOf('http://') < 0 || url.indexOf('https://') < 0) {
      url = 'http://' + url;
    }
    // 过滤掉不需要token的请求
    if (!needToken.length) {
        req = req.clone({
            url,
            headers: req.headers.set('token', sessionStorage.getItem('token'))
          });
    } else {
        req = req.clone({
            url
          });
      
    }
    return next.handle(req).pipe(
      tap(
        event => {
          if (event instanceof HttpResponse) {
            
          }
        },
        error => {
          // token过期 服务器错误等处理
          console.log(error)
          根据业务来判断
        })
    );
  }
}

再创建一个index.ts

import { HTTP_INTERCEPTORS } from '@angular/common/http';

import { CommonInterceptor } from './authInterceptor';

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

];

最后在app.module

import {httpInterceptorProviders  } from "./common/providers/index"

providers: [
    httpInterceptorProviders
  ],

注意:如果用户直接没有通过登录跳转路由,拦截里面有一个BUG

会报错

 

加上这一句,return of(1),直接return 会报错

You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array,

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值