angular-ui / ui-router

The de-facto solution to flexible routing with nested views in AngularJS
http://ui-router.github.io/
MIT License
13.53k stars 3k forks source link

.state data undefined on page refresh #2852

Closed zymr-keshav closed 8 years ago

zymr-keshav commented 8 years ago

as in new angular-ui-router v1.0.0alpha0 ,$stateChangeStart has been deprecated so using $transitions.on* hooks but not getting proper information where it has to written in .config block on in .run block?

I have tried to check authentications of HOME page in .config with below code


$stateProvider
        .state("home", {
            url: '/home',
            templateUrl: './home/home.html',
            controller: 'HomeController',
            requiresAuth: true,
            data : { pageTitle : 'Home', authorizedRoles: [USER_ROLES.admin, USER_ROLES.editor] }
 });
$transitionsProvider.onBefore({to: function(state) { return state.requiresAuth; } },
        function($transition$, $state, AuthService) {
            console.log(arguments);
            var from = $transition$.to().name;
            console.log(from);
            if(!AuthService.isAuthenticated()) {
                return $state.go("login", {referral : from});
            } else {
                console.log('I m logged in');
                var roles = $state.current.data.authorizedRoles;
                if(AuthService.isAuthorized(roles)) {
                    console.log('Authorized');
                }
            }
    });

it's working fine so far but when I refresh the same HOME page.. it gives error of undefined data property

see the plunker for the issue. when it asking for login, write anything in username and password

christopherthielen commented 8 years ago

var roles = $state.current.data.authorizedRoles;

should probably be

var roles = $transition$.to().data.authorizedRoles;

zymr-keshav commented 8 years ago

Thanks. I have one more confusion here

when to use .onBefore and when to use .onEnter or .onStart()

suppose user is logged in but not authorized then where do we write that logic? in resolve of .state ? or in .onStart or in onEnter()