我正在使用$stateProvider
,所以我有很多州。
考虑以下情况:
用户已经注销,他直接在浏览器中输入网址,如www.example.com/home
,我应该将其重定向到登录页面,即www.example.com/login
如何实现这个?其中一种方法是检查会话在运行块中是否处于活动状态。在运行块中调用后端API是一个好习惯吗?
更新: 根据Ryan的建议,它会调用后端api来检查用户是否已登录
$transitions.onBefore({to: 'home'}, function(transition) {
var $state = transition.router.stateService;
let promise = jsonService.heartBeat()
promise.then(data => {
if(!data.hasOwnProperty('data')) {
$state.go('login')
}
}, () => {
$state.go('login')
})
});
答案 0 :(得分:1)
Levi's的答案对于UI-Router 1.0版本是正确的。对于UI-Router 1.0,不推荐使用$stateChangeStart
等状态更改事件,这将不再有效。您可以改为使用$transitions
服务。
function run ($transitions, Auth) {
// 'to' param is the state name; 'main.**' will match 'main' and all sub-states
$transitions.onBefore({to: 'main.**'}, function (transition) {
var $state = transition.router.stateService;
if (!Auth.isAuthenticated()) {
$state.go('login');
}
});
}
run.$inject = ['$transitions', 'Auth'];
app.run(run);
答案 1 :(得分:0)
stateChangeStart
事件,然后检查当前状态是否需要身份验证。如果是,请检查用户是否已登录。
angular.module('portfolio.manager').config(function ($logProvider, $stateProvider) {
'use strict';
$stateProvider
.state('portfolio.manager', {
url: '/manager',
resolve: {
portfolioAuthService: 'portfolioAuthService',
User: function(portfolioAuthService){
return portfolioAuthService.getUser();
},
Portfolios: function (User, portfolioManagerService) {
return portfolioManagerService.getPortfolios();
}
},
data: {
requiredAuthentication: true
},
views: {
'main@': {
templateUrl: 'app/portfolio/manager/portfolio-manager.html',
controller: 'PortfolioManagerCtrl'
},
'no-portfolios@portfolio.manager': {
templateUrl: 'app/portfolio/manager/partials/no-portfolios.html'
},
'create@portfolio.manager': {
templateUrl: 'app/portfolio/manager/partials/create.html'
}
}
})
})
.run(run);
run.$inject = ['$rootScope','$state','loggedIn'];
function run($rootScope,$state,loggedIn){
$rootScope.$on('$stateChangeStart',function(e,toState){
if ( !(toState.data) ) return;
if ( !(toState.data.requiredAuthentication) ) return;
var _requiredAuthentication = toState.data.requiredAuthentication;
if (_requiredAuthentication && !loggedIn.checkUser() ){
e.preventDefault();
$state.go('portfolio.login', { notify: false });
console.log('not authorized');
}
return;
});
};