如何在角度拦截器中执行重定向? [英] How do I preform a redirect in an angular interceptor?
问题描述
我对angular还是很陌生,我想知道在拦截器中处理重定向的最佳方法.
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-router,角度为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');
下面的完整代码
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);
这篇关于如何在角度拦截器中执行重定向?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!