IanDess
IanDess

Reputation: 697

When is "onEnter" exactly executed

I'm looking for a best way to redirect my users from login/register form if they are already properly authenticated (and vice-versa)

So is it a good idea to do it onEnter? Will that function be executed before the associated controllers? Example:

...
.state('auth', {
    templateUrl: "auth.html",
    controller: 'PBAuthController as PBAuth',
    onEnter:  skipIfLoggedIn
})
...
function skipIfLoggedIn($q, $auth, $state) {
    var deferred = $q.defer();
    if ($auth.isAuthenticated()) {
        $state.go('backend');
    } else {
        deferred.resolve();
    }
    return deferred.promise;
}

Upvotes: 0

Views: 166

Answers (1)

Phil
Phil

Reputation: 164729

I just did a quick test and onEnter fires before the controller however there doesn't appear to be any way to prevent the controller from being instantiated.

In any case, here's how I've handled redirects in onEnter. The only thing to watch out for is to not interrupt the current state transition. You do this by waiting for the $state.transition promise to resolve...

onEnter: function($state, $auth) {
    return $auth.isAuthenticated() && $state.transition.then(function() {
        return $state.go('backend');
    });
}

Upvotes: 1

Related Questions