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
中的success
和error
中单独进行处理,可能如下:
$.ajax({ url: '/test', dataType: 'json', statusCode: { //对响应状态码进行拦截 404: function(){ alert("找不到页面"); }, 403: function(){ alert("没有权限"); } ...... }, success: function(){ //对成功响应进行处理 }, error: function(){ //对响应错误进行处理 }});
&esmp; 上面angular
拦截器中有写到$q
,$q
是angular
中的提供promise
服务的模块,可以去网上搜一下,有很多参考资料,这里不进行详解了。记住几个常用的接口就行了,defer
,resolve
,reject
,notify
。参考官方文档
阅读全文
1 0
- Angular统一拦截器(httpInterceptor)
- Angular 拦截器(403、401)
- Angular拦截器
- angular JS 拦截器总结
- Angular $http拦截器介绍与使用
- Angular $http拦截器介绍与使用
- Angular $http拦截器计算请求耗时
- struts2拦截器使用(用户session失效后的统一页面指向)
- OKHttp使用拦截器(Interceptor)POST与GET方法,统一封装传公共参数
- Spring mvc拦截器+angular js拦截器 做用户登录拦截控制
- angular 路由拦截
- Angular Universal(统一平台)笔记
- 使用方法拦截器MethodInterceptor和AOP统一处理log
- Spring方法拦截器MethodInterceptor和AOP统一处理log
- 使用方法拦截器MethodInterceptor和AOP统一处理log
- 使用方法拦截器MethodInterceptor和AOP统一处理log
- OkHttp3 Interceptor 拦截器的使用 统一追加参数
- 企业实战之Spring拦截器《统一参数校验》
- CSS3中的变形功能-transform功能
- Linux/Android系统知识之Linux入门篇--编写Linux驱动
- AVLTree
- ExtJs 解决多对一映射问题
- hpuoj 【1039】一二三四【同余定理】
- Angular统一拦截器(httpInterceptor)
- Redis的持久化之AOF方式
- Python-20 集合:唯一
- javase复习(二)--Comparable与Comparator的区别
- Notepad++ 中NppExec 插件的安装
- 分解质因数代码
- SpringBoot快速入门
- 杭电acm—2078 复习时间
- MySql基础