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, next: HttpHandler): Observable> {
    // 先补全请求协议
    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

会报错

 

angularcli 拦截器封装_第1张图片

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

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

你可能感兴趣的:(Angular)