您可以通過添加在.state
數據屬性一個布爾參數實現這一目標,我們說requiresAuth
和檢查也.RUN塊;
下面
是爲
在的.config塊
$stateProvider
.state("register", {
url: '/register',
templateUrl: 'register.html',
controller:'UserController',
controllerAs: 'vm',
data: {
requiresAuth: false,
pageTitle: 'Register'
}
})
.state("dashboard", {
url: '/dashboard',
templateUrl: 'dashboard.html',
controller:'OtherController',
controllerAs: 'vm',
data: {
requiresAuth: true,
pageTitle: 'Dashboard',
authorizedRoles: ['WHATEVER_ROLE']
}
});
和.RUN塊
var stateChangeStart = $rootScope.$on('$stateChangeStart', function(event, toState, toParams) {
if (AuthService.isAuthenticated()) {
// if user trying to access register/forgot page after login than redirect to dashboard
if (!toState.data.requiresAuth) {
event.preventDefault();
$rootScope.$broadcast(AUTH_EVENTS.notAuthorized);
}
// user is not authenticated and trying to access page which is not permissible than send back to dashboard
if (angular.isDefined(toState.data.authorizedRoles)) {
var roles = toState.data.authorizedRoles;
AuthService.isAuthorized(roles).catch(function() { // NOTE: here we are only handling with .catch block
event.preventDefault();
$rootScope.$broadcast(AUTH_EVENTS.notAuthorized);
});
}
}
// user is not authenticated than redirect to login
else if (toState.data.requiresAuth) {
event.preventDefault();
$rootScope.$broadcast(AUTH_EVENTS.notAuthenticated);
}
});
var notAuthenticated = $rootScope.$on(AUTH_EVENTS.notAuthenticated, function() {
$log.warn('not authenticated');
$state.go('login', null, {});
return;
});
var notAuthorized = $rootScope.$on(AUTH_EVENTS.notAuthorized, function() {
$log.warn('not authorized');
$state.go('dashboard');
return;
});
// DO NOT forget to destroy
$rootScope.$on('$destroy', notAuthenticated);
$rootScope.$on('$destroy', notAuthorized);
$rootScope.$on('$destroy', stateChangeStart);
提示僞代碼:不姓'next'作爲參數因爲它們是節點中的關鍵字並可能衝突 –
@ pro.mean必須有下一個作爲參數。如果不是應用程序不工作。 –
我的意思是說只改變參數名稱。請參閱下面的答案 –