任何时候,如果我们想要为请求添加全局功能,例如身份认证、错误处理等,在请求发送给服务器之前或服务器返回时对其进行拦截,是比较好的实现手段。
angularJs通过拦截器提供了一个从全局层面进行处理的途径。
四种拦截器
实现 request 方法拦截请求
1
2
3
4
|
request:
function
(config) {
// do something on request success
return
config || $q.when(config);
}
|
该方法会在 $http 发送请求后台之前执行,因此你可以修改配置或做其他的操作。该方法接收请求配置对象(request configuration object)作为参数,然后必须返回配置对象或者 promise 。如果返回无效的配置对象或者 promise 则会被拒绝,导致 $http 调用失败。
实现 requestError 方法拦截请求异常
1
2
3
|
requestError:
function
(rejection) {
// do something on request error return $q.reject(rejection);
}
|
有时候一个请求发送失败或者被拦截器拒绝了,请求异常拦截器会俘获那些被上一个请求拦截器中断的请求。它可以用来恢复请求或者有时可以用来撤销请求之前所做的配置,比如说关闭进度条,激活按钮和输入框什么之类的。
实现 response 方法拦截响应
1
2
3
|
response:
function
(response) {
// do something on response success
return
response || $q.when(response);}
|
该方法会在 $http 接收到从后台过来的响应之后执行,因此你可以修改响应或做其他操作。该方法接收响应对象(response object)作为参数,然后必须返回响应对象或者 promise。响应对象包括了请求配置(request configuration),头(headers),状态(status)和从后台过来的数据(data)。如果返回无效的响应对象或者 promise 会被拒绝,导致$http 调用失败。
实现 responseError 方法拦截响应异常
1
2
3
|
responseError:
function
(rejection) {
// do something on response error return $q.reject(rejection);
}
|
有时候我们后台调用失败了,也有可能它被一个请求拦截器拒绝了或者被上一个响应拦截器中断了。在这种情况下,响应异常拦截器可以帮助我们恢复后台调用。
拦截器核心
拦截服务工厂
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
var
app = angular.module(
"ajaxHttp"
, []);
app.factory(
"httpInterceptor"
, [
"$q"
,
"$rootScope"
,
function
($q, $rootScope) {
return
{
request:
function
(config) {
// do something on request success
return
config || $q.when(config);
},
requestError:
function
(rejection) {
// do something on request error
return
$q.reject(rejection)
},
response:
function
(response) {
// do something on response success
return
response || $q.when(response);
},
responseError :
function
(rejection) {
// do something on response error
return
$q.reject(rejection);
}
};
}]);
|
注册拦截工厂方法
1
2
3
|
app.config([
"$httpProvider"
,
function
($httpProvider) {
$httpProvider.interceptors.push(
"httpInterceptor"
);
}]);
|
示例
对401,404的拦截处理
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
app.config([
"$httpProvider"
,
function
($httpProvider) {
$httpProvider.interceptors.push(
'httpInterceptor'
);
}]);
app.factory(
"httpInterceptor"
, [
"$q"
,
"$injector"
,
function
($q, $injector) {
return
{
"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) {
console.log(
"404!"
);
return
$q.reject(response);
}
}
};
]);
|
以上内容给大家分享快速学习AngularJs HTTP响应拦截器 的相关知识,希望大家喜欢,同时感谢大家一直以来对脚本之家网站的支持。