文章15
标签3
分类5

Angular 请求响应拦截

请求拦截

import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class Interceptor implements HttpInterceptor {
    intercept(req: HttpRequest<any>,next: HttpHandler): Observable<HttpEvent<any>> {
       const token :string | null = window.localStorage.getItem('_token');
        if (token) {
            // 设置请求头
            req = req.clone({
                setHeaders: {
                    'token': `${token}`,
                    'Content-Type': 'application/json'
                }
            });
        }
        return next.handle(req);
    }
}

请求的时候 请求头加 token

响应拦截

import { HttpInterceptor, HttpRequest, HttpHandler } from '@angular/common/http';
import { Injectable } from '@angular/core';
    import { Router ,NavigationExtras} from '@angular/router';
import { catchError, retry } from 'rxjs/operators';
@Injectable()
export class CatchErrorInjector implements HttpInterceptor {
  constructor(public router:Router){}
  intercept(req: HttpRequest<any>, next: HttpHandler) {
    return next.handle(req).pipe(
      catchError(err => {
        // token 判空处理
        // 页面响应 loadin 加载
        // 登录持久化
        // 页面骨架
        // 路由跳转
        if(err.error=== 'Unauthorized'){
          console.log('token过期')
          this.router.navigate(['login'])
        }
        throw err;
      }),
    );
  }
}

响应的时候 判断 token 是否过期

// 拦截器
import { HTTP_INTERCEPTORS } from '@angular/common/http';
// 请求
import { Interceptor } from "../server/interceptors";
// 响应
import { CatchErrorInjector } from "../server/CatchErrorInjector";
const HttpInterceptorProviders = [
  { provide: HTTP_INTERCEPTORS, useClass: Interceptor, multi: true },
  { provide: HTTP_INTERCEPTORS, useClass: CatchErrorInjector, multi: true },
]

这是两个服务所以我们要 根模块 providers里引用它

">