Angularjs 判断服务器401错误

之前在github上有篇判断augularjs401状态码的:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
var logsOutUserOn401 = function($location, $q, SessionService, FlashService) {
var success = function(response) {
return response;
};
var error = function(response) {
if(response.status === 401) {
SessionService.unset('authenticated');
$location.path('/login');
FlashService.show(response.data.flash);
}
return $q.reject(response);
};
return function(promise) {
return promise.then(success, error);
};
};
$httpProvider.responseInterceptors.push(logsOutUserOn401);

今天用时才发现$httpProvider.responseInterceptors方法已经被官方弃用了。
改写了方案如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
app.factory('errorInterceptor', ['$q', '$rootScope', '$location','FlashService',
function ($q, $rootScope, $location,FlashService) {
return {
request: function (config) {
return config || $q.when(config);
},
requestError: function(request){
return $q.reject(request);
},
response: function (response) {
return response || $q.when(response);
},
responseError: function (response) {
if(response.status === 401) {
// SessionService.unset('authenticated');
FlashService.show(response.data.error);
$location.path('/login');
}
if (response && response.status === 404) {
}
if (response && response.status >= 500) {
}
return $q.reject(response);
}
};
}]);

在app.js config 方法调用时:

1
$httpProvider.interceptors.push('errorInterceptor');