详解AngularJS用Interceptors来统一处理HTTP请求和响应
Web开发中,除了数据操作之外,最频繁的就是发起和处理各种HTTP请求了,加上HTTP请求又是异步的,如果在每个请求中来单独捕获各种常规错误,处理各类自定义错误,那将会有大量的功能类似的代码,或者使用丑陋的方法在每个请求中调用某几个自定义的函数来处理。这两种方法基本都不是靠谱之选。好在AngularJS提供了Interceptors——拦截战斗机——来对应用内所有的XHR请求进行统一处理。
主要功能
Interceptors有两个处理时机,分别是:
- 其它程序代码执行HTTP请求之后,在实际从浏览器发出请求之前,即处理请求
- 得到请求的响应之后,在交给其它程序代码处理之前,即处理请求的响应
所以,不难理解它可以用于如下几个方面:
- 全局处理错误
- 统一进行身份验证一类的处理
- 对所有发出去的请求进行预处理
- 对所有收到的响应进行预处理
- 做一些增强用户体验的操作,例如显示一个进度条
基本使用
先来看看最基本的使用:
varapp=angular.module('app',[]); //定义一个Service,稍等将会把它作为Interceptors的处理函数 app.factory('HttpInterceptor',['$q',HttpInterceptor]); functionHttpInterceptor($q){ return{ request:function(config){ returnconfig; }, requestError:function(err){ return$q.reject(err); }, response:function(res){ returnres; }, responseError:function(err){ if(-1===err.status){ //远程服务器无响应 }elseif(500===err.status){ //处理各类自定义错误 }elseif(501===err.status){ //... } return$q.reject(err); } }; } //添加对应的Interceptors app.config(['$httpProvider',function($httpProvider){ $httpProvider.interceptors.push(HttpInterceptor); }]);
进一步了解
实际的Interceptor处理函数中,return了一个包含四个成员的对象,这四个成员都不是必须的,可以按实际情况指定一二,分别如下:
- request:接收一个参数,它是$http中的标准config对象,同时也需要返回一个标准config,此时可以添加各类身份验证信息,同时也可在此启动进度条
- requestError:当有多个Interceptor的时候,requestError会在前一个Interceptor抛出错误或者执行$q.reject()时执行,接收的参数就对应的错误
- response:接受一个请求对象参数,可以不处理就直接返回,此时也可以将进度条显示为成功完成,当然,如果后端API返回自定义错误时,HTTP的状态码仍然是200得话,便在这里处理自定义错误,也可以对返回数据做一些处理,注意要将进度条置为完成
- responseError:这个是重头戏,即可以处理标准的Http错误,如服务器没有响应时,或者PHP之类的CGI经常出现的502一类,还可以处理HTTP状态码不是200的各类自定义错误
上面四个中,前两个是请求的前置处理,后两个是针对请求的响应的处理。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。