angularjsangular-ui-routerangular-transitions

What is Equivalent of next in $routeChangeStart in $transitions


I am building a permission-based access control app in angularjs. I want the parameter in $transitions which would be equivalent to 'next' parameter in $routeChangeStart.

  function ($rootScope, $state, $transitions, LoginService) {
        console.log('------------------in app.js run');
        $state.go('login');
        $transitions.onStart({}, function ($transitions) {
                var newToState = $transitions.$to();
                if(checkPermissionForView(// param similar to next))
        });

    }

I have a service defined which checks if the logged in user has the permission to access the view

  checkPermissionForView : function (view) {
                if (!view.requiresAuthentication) {
                    return true;
                }

                return userHasPermissionForView(view);
            }

  userHasPermissionForView : function(view){
                if(!isLoggedIn()){
                    return false;
                }
            }

  isLoggedIn : function () {
                var user = JSON.parse(localStorage.getItem("user"));
                console.log(user);
                return user != null;
            }

As you can see I want to pass 'next' information to service. Does $transitions.$to() yield the same result as next in $routeChangeStart('next')? I am new to this. TIA


Solution

  • Yes, use Transition.to() to get the state that will be activated.

    See the docs for the Transition class for more details.

    function ($rootScope, $state, $transitions, LoginService) {
            console.log('------------------in app.js run');
            $state.go('login');
            $transitions.onStart({}, function (transition) {
                    var newToState = transition.to();
                    if(!checkPermissionForView(newToState)) {
                             return $state.target('login');
                    }
            });
    }
    

    ...

    checkPermissionForView : function (state) {
                    if (!state.requiresAuthentication) {
                        return true;
                    }
    
                    return userHasPermissionForState(state);
                }
    
      userHasPermissionForState : function(view){
                    if(!isLoggedIn()){
                        return false;
                    }
                }
    
      isLoggedIn : function () {
                    var user = JSON.parse(localStorage.getItem("user"));
                    console.log(user);
                    return user != null;
                }
    

    I highly recommend reading the Transition Hooks Guide