1

Im trying to use a promise to prevent a state from loading in UI Router $resolve.

$stateProvider.state('base.restricted', {

    url:'/restricted',
    templateUrl: 'views/restricted.html',
    controller: 'restrictedCtrl',

    resolve: { // user must be logged-in to proceed

        // authentication service checks session on back-end
        authenticate: function ($q, $state, $timeout, AuthService){

            AuthService.validate(token).then(function(res){ 

                if( res.data.response.status===1 ) { // authenticated!

                    return $q.resolve(); // load state

                } else { // authentication failed :(

                    $timeout(function() { $state.go('base.notfound') }); // load not found page
                    return $q.reject(); // do not load state
                }

            });
        } 
    }

})

This scheme works in terms of redirecting the user based on authentication results, but it looks like, upon failed authentication, the controller is still being loaded for a brief instant before the user is re-directed to the "not found" state.

I believe the reason is because Im running AuthService within resolve, but in an asynchronous manner. So the controller is loaded while AuthService does its thing but is then redirected once the callback function executes.

But isnt resolve inherently supposed to be blocking? That is, the controller doesnt load until resolve is "resolved"?

AuthService is basically this, fyi:

.service('AuthService', function($http){

    this.validate = function(token){

        return $http.get('http://my.api/validate/'+token);
    }
});

How can I modify this code to prevent loading until AuthService's callback function has completed.

1 Answer 1

2

You should return a promise immediately, instead of doing so after the response from the service comes back:

return AuthService.validate(token).then(function(res){ ... }

Otherwise the router sees no return value instead of a promise, so it thinks it's OK to load the state. Then later when your AJAX request returns you end up redirecting, which is why you see a flicker.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the answer and the explanation I had the same problem

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.