问题描述
在我的 angularjs 应用程序中,我正在检查用户是否登陆登陆页面并且已经通过身份验证,然后将他重定向到主页.
In my angularjs app, I am checking if user lands on landing page and is already authenticated, then redirect him to home page.
.state('landingpage', {
abstract: "true",
url: "/landingpage",
templateUrl: "app/landingpage/landingpage.html",
resolve: {
AutoLoginCheck: ['$state', '$window', function ($state, $window) {
if($window.localStorage.access_token != null)
{
if($window.sessionStorage.access_token == null) {
$window.sessionStorage.access_token = $window.localStorage.access_token;
}
UserInfoService.SetUserAuthenticated(true);
// it is not redirecting
return $state.go('app.home');
}
}]
}
})
问题是,尽管所有解析代码都成功运行,但用户并没有被重定向到 app.home.有人能说出为什么会这样吗?
The problem is that though all the resolve code is successfully run, user is not getting redirected to app.home. Can someone tell why this happens?
注意:状态app"也有一个解析,它获取要在app.home"状态下显示的数据.
Note: The state 'app' also has a resolve in which it fetches the data to be displayed in 'app.home' state.
推荐答案
您的问题可以有两种解决方案
There can be two solutions to your problem
首先,您可以发出一个事件,侦听器将处理您的状态转换.你可以在父控制器的任何地方实现监听器
Firstly you can emit an event and the listener will handle your state transition. You can implement the listener in anywhere in a parent controller
其次,您可以实现 $stateChangeStart 钩子并在那里检查您的重定向条件
Secondly you can implement the $stateChangeStart hook and check your redirection condition there
$rootScope.$on('$stateChangeStart', function (event, toState) {
if (toState.name === 'landingpage') {
if (!isAuthenticated()) { // Check if user allowed to transition
event.preventDefault(); // Prevent migration to default state
$state.go('home.dashboard');
}
}
});
这篇关于Angular ui-router $state.go 不在解析内重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!