如何在角度拦截器中执行重定向? [英] 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,angular 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屋!