我想在我的Angular应用中制作一个或多或少的通用错误处理程序。
例如,我收到带有此链接的邮件:mysite/messages/151
单击此邮件:如果未登录,我的框架将返回403(故意)。
所以我创建了这个工厂。目前,它仅查找403错误,然后将用户路由到登录页面。
app.factory('httpRequestInterceptor', ['$q', '$location', '$rootScope', function($q, $location) {
return {
'responseError': function(rejection) {
if (rejection.status === 403) {
$location.path('/user/login');
return $q.reject(rejection);
}
}
};
}]);
在app.config中,我添加了以下行:
app.config(['$httpProvider', function($httpProvider)
{
$httpProvider.interceptors.push('httpRequestInterceptor');
现在,当我收到403时,我将转到正确的路径:/user/login
到现在为止还挺好。
但是...我想以某种方式添加$ state,以便我知道调用的URL是什么(messages/151),以便我可以返回正确的位置并显示该消息。
我不能在工厂中使用$ state(由于一些我还不了解的技术东西而出错($ http vs $ state?),所以现在我很困惑如何完成这些工作。
所以,我想要:
1)在URL上的403错误进入登录状态(有效)
2)从用户(工作)获取登录凭据
3)登录成功后转到URL(不是一个线索)
也许我应该使用另一种方法,但是我无法解决这个问题。所以希望有人可以帮助我吗?
最佳答案
好的,这就是我想出的。谢谢!
/**
* Error handling on httpRequests.
*
* generic: use rejection.status like: if (rejection.status === 403) {return $q.reject(rejection);}
* custom: check fromState['current']['name'] for state name
*
*/
app.factory('httpRequestInterceptor', ['$q', '$location', '$injector', '$timeout', '$stateParams', function($q, $location, $injector, $timeout, $stateParams) {
return {
'responseError': function(rejection) {
var fromState = $injector.get('$state');
$timeout(function() {
switch (fromState['current']['name']) {
case 'root.messages':
$injector.get('$state').go('root.login', $stateParams,
{location: false});
break;
}
}, 2000);
return $q.reject(rejection);
}
};
}]);