Angular统一拦截器(httpInterceptor)

来源:互联网 发布:netty 聊天室架构源码 编辑:程序博客网 时间:2024/05/22 15:49

需求背景:前端每向后台发送请求之前,或者发送请求出现了什么错误,以及接收后台一次响应之后或者响应出错的时候,通常都会根据具体的需求(请求转换,更改head,加token,响应错误拦截处理,加密解密等)做一些额外处理。如果每一发送请求的地方都进行处理,无疑很有灵活性,但也将无关的代码侵入了业务逻辑中。因此为解决这个问题就有了httpInterceptor

angular中提供了这样的拦截器接口$httpProvider.interceptors,只要按格式要求定一个httpInterceptor(这个名字是自定义的,但是其拥有的属性必须要严格按照一定格式)的factory。可能像下面这个样子:

var myApp = angular.module("myApp", []); //首先定一个app //定义http拦截器httpInterceptor,这个factory返回的对象可以拥有responseError,response,request,requestError这些属性,分别对应拦截的处理。myApp.factory('httpInterceptor', [ '$q',function($q) {     var httpInterceptor = {       'responseError' : function(response) { //响应错误拦截        //这里可以对不同的响应错误进行处理,比如根据返回状态码进行特殊处理        switch(response。status) {            case 404:                alert("找不到页面");                break;            case 403:                alert("没有权限");                break;            defalut:                ....        }        return $q.reject(response);       },       'response' : function(response) {     //响应拦截        //这里可以对所有的响应的进行处理        return response;       },       'request' : function(config) {        //请求拦截        //这里可以对所有的请求进行处理        return config;       },       'requestError' : function(config){    //请求错误拦截        //这里可以对所有的请求错误进行处理        return $q.reject(config);       }     }   return httpInterceptor; }//定义了httpInterceptor之后,需要手动添加到$httpProvider.interceptors中去才能让拦截器生效myApp.config([ '$httpProvider', function($httpProvider) {   $httpProvider.interceptors.push('httpInterceptor'); //添加拦截器} ]);

使用还是比较简单的,但是* 需要注意是拦截的请求只能是通过angular中的$http发送的请求和响应才能被httpInterceptor拦截,ajax发送或其他方式的请求不能够被httpInterceptor拦截! *,所以当使用其他方式发送请求时,在httpInterceptor中不能被拦截的时候要清楚这一点。如果使用ajax发送请求,就需要在ajax中的successerror中单独进行处理,可能如下:

$.ajax({    url: '/test',    dataType: 'json',    statusCode: {  //对响应状态码进行拦截        404: function(){            alert("找不到页面");        },        403function(){            alert("没有权限");        }        ......    },    success: function(){        //对成功响应进行处理    },    error: function(){        //对响应错误进行处理    }});

&esmp; 上面angular拦截器中有写到$q$qangular中的提供promise服务的模块,可以去网上搜一下,有很多参考资料,这里不进行详解了。记住几个常用的接口就行了,deferresolverejectnotify。参考官方文档