1

Im just learning ui-router resolve and would like to simply redirect my state if the user is not logged-in.

It seems I cannot simply use $state.go inside the callback function.

Here is my code:

.state('base.user', {
  url: '/user',
  templateUrl: 'views/user.html',
  controller: 'userCtrl',
  resolve: {
    test: function($state, $q) {
      var deferred = $q.defer();
      if (!loggedIn()) { // resolves to false when not logged-in
        deferred.reject();
        $state.go('base.test'); // ** Throws "Possibly unhandled rejection" error
      } else {
        deferred.resolve();
        /* and maybe do some more stuff.. */
      }
    }
  }
})

I know this is often done with services and things like that, but for now, I would just like a simple working example.

2 Answers 2

2

The way we decided to handle it was to listen to $stateChangeError and if the error thrown contained a path, then go to that path.

$rootScope.$on('$stateChangeError', function(toState, toParams, fromState, fromParams, error) {
  if (error.state) {
    $state.go(error.state, error.stateParams);
  }
});

And in you resolve:

test: function($q) {
  var deferred = $q.defer();
  if (!loggedIn()) {
    deferred.reject({state: 'base.test'});
  } else {
    deferred.resolve();
  }
  return deferred.promise;
}
Sign up to request clarification or add additional context in comments.

Comments

1

Implement the $stateChangeStart hook and check your redirection condition there

$rootScope.$on('$stateChangeStart', function (event, toState) {      
     if (toState.name === 'base.user') {              
       if(!loggedIn()) { // Check if user allowed to transition                  
            event.preventDefault();   // Prevent migration to default state                  
            $state.go('base.test');           
        }
      }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.