使用UI路由器,当用户访问需要登录的页面时,我们希望将它们重定向回原来的网址。
例如,
/account/profile --> LOGIN PAGE (/login) --> /account/profile
/someother/requiredLogin/path --> LOGIN PAGE (/login) --> /someother/requiredLogin/path
我的路线:
$stateProvider
.state('accountProfile', {
url: '/account/profile',
data: {
requiresLogin: true
},
views: {
'': {
templateProvider: function($templateCache) {
return $templateCache.get('templates/profile.html');
}
}
},
})
.state('anotherPage', {
url: '/someother/path',
data: {
requiresLogin: true
},
views: {
'': {
templateProvider: function($templateCache) {
return $templateCache.get('templates/other.html');
}
}
},
})
在我的应用程序运行块中,我有:
.run(['$rootScope', '$state', 'LoginService',
function($rootScope, $state, LoginService) {
// Change title based on the `data` object in routes
$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
var requiresLogin = toState.data.requiresLogin;
if (requiresLogin && !LoginService.check()) {
event.preventDefault();
$state.go('login');
}
});
}
])
正如您所看到的,我在为每条路线添加requiresLogin
时做了基本工作,只是将路由重定向到login
。如何跟踪原始URL并在登录后将其重定向到它?
答案 0 :(得分:6)
更新您的登录状态配置,以包含要在登录时重定向到的状态名称的默认参数(toState)以及使用原始状态更改传递的任何参数(toParams)。如果您没有定义默认值,那么当您在登录控制器中检查它们时,$ state.params将始终为空 - 即使您提供了$ stateChangeStart处理程序的值!
.state('login', {
data: {'requiresLogin': false},
params: {
'toState': 'profile', // default state to proceed to after login
'toParams': {}
},
url: 'login',
})
修改您的运行块以捕获并传递请求的(未授权的)状态:
$state.go('login', {'toState': toState.name, 'toParams': toParams});
在您的登录控制器成功处理程序中,以下内容将使您进入$ stateChangeStart中指定的状态或状态配置中声明的默认状态:
$state.go($state.params.toState, $state.params.toParams);