我试图实现Angular Interceptor for Exceptions。至少一个人。我有一个令牌,当它老了enogh后端抛出TokenAlmostExpired exception
。此例外包含errorCode = 101
。在拦截器中,我检查代码是101,然后我需要将POST request
发送到后端/refresh endpoint
,这样我就可以刷新令牌了。
.factory('errorInjector',['$injector', function ($q, $injector) {
var vm = this;
var errorInjector = {
'response': function (response) {
console.log(response);
return response;
},
'responseError': function (rejection) {
if (JSON.stringify(rejection.data.errorCode) === JSON.stringify(101)) {
vm.getRefreshToken();
}
return $q.reject(rejection);
}
};
return errorInjector;
}]);
和
.config(['$httpProvider', function ($httpProvider) {
$httpProvider.interceptors.push('errorInjector');
}]);
$ HTTP
但是在拦截器级别存在问题,我不能仅依赖于$http
,因为Circular dependency found: $http <- errorInjector <- $http <- $templateFactory <- $view <- $state
$范围
而且我无法将getRefreshToken()
函数放到$scope
,因为$ scope依赖项也会提供&#39;循环依赖&#39;。
$注射器
var http = $injector.get('$http');
也不起作用,让我更加兴奋。
那么如何在拦截器中捕获异常然后从那里执行$ http请求呢?
答案 0 :(得分:1)
拦截器
(function (angular) {
'use strict';
angular.module('services').factory("httpInterceptor", [
'errorLauncher',
'$q',
function (errorLauncher, $q) {
return {
'requestError': function (rejection) {
if (rejection.status === 101) {
errorLauncher.pushInErrorMessage(rejection);
}
return $q.reject(rejection);
},
'responseError': function (rejection) {
if (rejection.status === 101) {
errorLauncher.pushInErrorMessage(rejection);
}
return $q.reject(rejection);
}
};
}]);
})(angular);
和错误处理程序服务
(function (angular) {
'use strict';
angular.module('services').factory("errorLauncher", [
'$rootScope',
function ($rootScope) {
return {
'pushInErrorMessage': function (rejection) {
$rootScope.$emit('theTokenWillDieSoon');
}
};
}]);
})(angular);
现在是主app控制器
(function (angular) {
'use strict';
angular.module('controllers').controller("globalCtrl", [
'$rootScope',
'$http',
function ($rootScope, $http) {
$rootScope.$on('theTokenWillDieSoon', function () {
// http from here
});
}]);
})(angular);
答案 1 :(得分:0)
.factory(&#39; errorInjector&#39;,[&#39; $ injector&#39;,function($ q,$ injector){....}]);
更改为:
.factory(&#39; errorInjector&#39;,[&#39; $ q&#39;,function($ q){....}]);
答案 2 :(得分:0)
所以我用服务完成了它。谢谢大家!
<强>拦截器:强>
2 -> 2aabbcc
COLUMN3:bb<>b
4 not in temp2
<强> refreshTokenService:强>
.factory('errorInjector',['$injector', function ($q, $injector) {
var errorInjector = {
'response': function (response) {
....
},
'responseError': function (rejection) {
if (JSON.stringify(rejection.data.errorCode) === JSON.stringify(101)) {
var refreshTokenService = $q.get('refreshTokenService');
refreshTokenService.refreshTokenService();
$.notify({message: data.data.detailMessage}, {type: 'warning'});
}
return $q.reject(rejection);
}
};
return errorInjector;
}]);
}]) ;