zoukankan      html  css  js  c++  java
  • angular6之http请求拦截器

    在前端项目中我们往往需要对每次请求做一些统一的处理,比如请求结果session过期处理,在header头部加上验证参数token等等,这个时候就需要用到拦截器。

    由于angular中http请求,依赖@angular/common/http模块,将HttpInterceptor,HttpRequest,HttpResponse等对象引入

    import {
        HttpInterceptor,
        HttpRequest,
        HttpHandler,
        HttpErrorResponse,
        HttpHeaderResponse,
        HttpResponse,
    } from '@angular/common/http';
    

      引入模块后,我们要实现HttpInterceptor接口

    export class MyInterceptor implements HttpInterceptor {
        constructor (){}
    }
    

      具体的拦截器部分实现:

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<
        | HttpHeaderResponse
        | HttpResponse<any>
      > { 
    let req = request.clone({param1:'',param2:''});//这里可以在请求中加参数 return next.handle(req).pipe( mergeMap((event: any) => { // 正常返回,处理具体返回参数 if (event instanceof HttpResponse && event.status === 200) return this.handleData(event);//具体处理请求返回数据 return of(event); }), catchError((err: HttpErrorResponse) => this.handleData(err))) }

      在平常我们的业务中往往服务端返回200,但是有可能是业务上出错,比如说请求的参数不对,session过期没有通过验证等等,这个时候需要我们做统一处理

    private handleData(
            event: HttpResponse<any> | HttpErrorResponse,
          ): Observable<any> {
            // 业务处理:一些通用操作
            switch (event.status) {
              case 200:
                if (event instanceof HttpResponse) {
                    const body: any = event.body;
                    if (body && body.rc == 3) {
                        this.goTo('/test');
                    }
                }
                break;
              case 401: // 未登录状态码
                this.goTo('/login');
                break;
              case 404:
              case 500:
               ……
              break;
              default:
              return of(event);
          }
    

      这里我们对不同返回状态做同的统一处理。

    最后我们将拦截器模块引入到app.module.ts跟模块中。基本就完成了

    import { MyInterceptor } from './myIntercept'
    @NgModule({
         ……
         providers: [{ provide: HTTP_INTERCEPTORS, useClass: MyInterceptor, multi: 
                         true }]
        ……
    })
    

      注:本文部分代码参考了ng-alain中拦截器的写法,如果想了解可以参考https://github.com/cipchk/ng-alain

  • 相关阅读:
    线性表——(2)单向链表
    线性表——(1)顺序表
    UVa 1592 数据库
    UVa 12096 集合栈计算机
    Python 协程
    Python 多线程及进程
    Python 日志(Log)
    Python 函数式编程
    Python基础
    DB2 获取前两天的数据
  • 原文地址:https://www.cnblogs.com/leejay6567/p/9462758.html
Copyright © 2011-2022 走看看