I am trying to perform a basic security check to block users from accessing certain states depending on their set of permissions:
'use strict';
var autoExecApp = angular.module("myApp", ['ui.router']);
autoExecApp.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider){
$stateProvider
.state('index', {
url: '/index',
templateUrl: 'partials/index.html'
})
.state('permission', {
url: '/permission',
templateUrl: 'partials/permissions.html'
});
}]);
autoExecApp.run(['$rootScope', '$state', '$userRoles', function($rootScope, $state, $userRoles) {
$rootScope.$on('$stateChangeStart', function (event, toState, toParams) {
event.preventDefault();
$userRoles.hasPermissions(toState.name).then(function(data) {
var result = data === "true";
if (!result) {
$state.go('permission');
}
else {
$state.go(toState.name, toParams ,{notify:false});
}
});
});
}]);
Now the problem is that my state change happens inside the promise. I would love to do it synchronously - as it really should be in this case, but I'm confused why it doesn't work asynchronously.
event.preventDefault() , . 2 . -, , "" ( ). , , $on , , .
- , , . , . , . - , , . , $state.go , , , $.
EDIT: , :
event.preventDefault();
$state.go(toState.name, toParams, {notify: false}).then(function() {
$rootScope.$broadcast('$stateChangeSuccess', toState, toParams, fromState, fromParams);
});
-, - , , preventDefault(); "$ stateChangeSuccess" . .