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

  • 相关阅读:
    DOM对象和JQuery对象的区别
    处理android手机html5页面中,点击text文本框无法自动获取焦点的处理方法
    ORACLE之VBO-5530无法删除用户的解决办法
    当oracle clob类型不能和group by并用,但是需要去除多列重复
    Android 4主线程访问网络
    Android: How to get Address from geolocation using Geocoder
    解决乱码的最后方法
    tomcat启动时自动运行代码
    android 组件隐蔽显示状态
    android模拟器Genymotion 连接eclipse项目
  • 原文地址:https://www.cnblogs.com/leejay6567/p/9462758.html
Copyright © 2011-2022 走看看