您的位置:首页 > 理论基础 > 计算机网络

angularJs HTTP响应拦截器

2015-07-30 17:22 531 查看
为何要用拦截器?

任何时候,如果我们想要为请求添加全局功能,例如身份认证、错误处理等,在请求发送给服务器之前或服务器返回时对其进行拦截,是比较好的实现手段。

angularJs通过拦截器提供了一个从全局层面进行处理的途径.

拦截器允许你:

通过实现 request 方法拦截请求: 该方法会在 http发送请求道后台之前执行,因此你可以修改配置或做其他的操作。该方法接收请求配置对象(requestconfigurationobject)作为参数,然后必须返回配置对象或者promise。如果返回无效的配置对象或者promise则会被拒绝,导致http 发送请求道后台之前执行,因此你可以修改配置或做其他的操作。该方法接收请求配置对象(request configuration object)作为参数,然后必须返回配置对象或者 promise 。如果返回无效的配置对象或者 promise 则会被拒绝,导致 http 调用失败。

通过实现 response 方法拦截响应: 该方法会在 http接收到从后台过来的响应之后执行,因此你可以修改响应或做其他操作。该方法接收响应对象(responseobject)作为参数,然后必须返回响应对象或者promise。响应对象包括了请求配置(requestconfiguration),头(headers),状态(status)和从后台过来的数据(data)。如果返回无效的响应对象或者promise会被拒绝,导致http 接收到从后台过来的响应之后执行,因此你可以修改响应或做其他操作。该方法接收响应对象(response object)作为参数,然后必须返回响应对象或者 promise。响应对象包括了请求配置(request configuration),头(headers),状态(status)和从后台过来的数据(data)。如果返回无效的响应对象或者 promise 会被拒绝,导致http 调用失败。

通过实现 requestError 方法拦截请求异常: 有时候一个请求发送失败或者被拦截器拒绝了。请求异常拦截器会俘获那些被上一个请求拦截器中断的请求。它可以用来恢复请求或者有时可以用来撤销请求之前所做的配置,比如说关闭进度条,激活按钮和输入框什么之类的。

通过实现 responseError 方法拦截响应异常: 有时候我们后台调用失败了。也有可能它被一个请求拦截器拒绝了,或者被上一个响应拦截器中断了。在这种情况下,响应异常拦截器可以帮助我们恢复后台调用。

拦截器的核心是服务工厂,通过向httpprovider.interceptors数组中添加服务工厂。在httpprovider.interceptors数组中添加服务工厂。在httpProvider中进行注册。

angularJs提供四种拦截器,其中两种成功拦截器(request、response),两种失败拦截器(requestError、responseError)。

在服务中添加一种或多种拦截器:

angular.module("myApp", [])
.factory('httpInterceptor', [ '$q', '$injector',function($q, $injector) {
var httpInterceptor = {
'responseError' : function(response) {
......
return $q.reject(response);
},
'response' : function(response) {
......
return response;
},
'request' : function(config) {
......
return config;
},
'requestError' : function(config){
......
return $q.reject(config);
}
}
return httpInterceptor;
}


然后使用$httpProvider在.config()函数中注册拦截器

angular.module("myApp", [])
.config([ '$httpProvider', function($httpProvider) {
$httpProvider.interceptors.push('httpInterceptor');
} ]);


实际的例子:(对401、404的拦截)

routerApp.config([ '$httpProvider', function($httpProvider) {
$httpProvider.interceptors.push('httpInterceptor');
} ]);

routerApp.factory('httpInterceptor', [ '$q', '$injector',function($q, $injector) {
var httpInterceptor = {
'responseError' : function(response) {
if (response.status == 401) {
var rootScope = $injector.get('$rootScope');
var state = $injector.get('$rootScope').$state.current.name;
rootScope.stateBeforLogin = state;
rootScope.$state.go("login");
return $q.reject(response);
} else if (response.status === 404) {
alert("404!");
return $q.reject(response);
}
},
'response' : function(response) {
return response;
}
}
return httpInterceptor;
}
]);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: