我如何preform重定向在角拦截 [英] How do I preform a redirect in an angular interceptor
问题描述
喜家伙我pretty新的角度,我对处理一个拦截器中的重定向的最佳方法的问题。
Hi guys I am pretty new to angular, and I had a question on the best way to handle a redirect within an interceptor.
我在我的应用程序的某些网页,我应该只能够访问,如果我有选择的帐户。所以,如果没有选择的帐户我希望路由用户页面,选择帐户。
I have certain pages in my app that I should only be able to access if I have an account selected. So if an account is not selected I want the route the user to page to select the account.
以下是我的失败尝试:
// within config
$httpProvider.interceptors.push(function($q, $injector){
return {
'request': function(config) {
var state = $injector.get('$state');
if(state.is('user.list')) {
var accountService = $injector.get('AccountService');
if(!accountService.accountSelected()){
// cancel the current request
var defer = $q.defer();
defer.resolve();
config.timeout = defer.promise;
state.go('account.select');
}
}
return config;
}
}
});
这是引起的无限循环的我。因为当 state.go
火灾某种原因 - 它被重新截获的状态仍为user.list
This is causing an infinite loop for me. For some reason when state.go
fires -- and it gets re-intercepted the state is still "user.list"
请注意:我使用的UI路由器,角1.2.6
Note: I am using ui-router, angular 1.2.6
另注:我觉得把这个的另一个地方是在state.resolve块
Another Note: The other place I thought of putting this was in a state.resolve block.
感谢您的帮助!
推荐答案
做这样
$injector.get('$state').transitionTo('public.login');
满code以下
var interceptor = ['$location', '$q', '$injector', function($location, $q, $injector) {
function success(response) {
return response;
}
function error(response) {
if(response.status === 401) {
$injector.get('$state').transitionTo('public.login');
return $q.reject(response);
}
else {
return $q.reject(response);
}
}
return function(promise) {
return promise.then(success, error);
}
}];
$httpProvider.responseInterceptors.push(interceptor);
这篇关于我如何preform重定向在角拦截的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!