user36322 February 2016

Controller doesn't wait for resolve

I have a resolve, but the controller seems to run before it finishes.

    $stateProvider.state('index', {
        url: '/',
        templateUrl: '/angular/general/index.general.html',
        resolve: {
            data: function(currentUser){
                currentUser.resolveLogin();
            }
        },
        controller: ['$state', 'currentUser', function($state, currentUser){
            console.log('3');
            if (currentUser.bLoggedIn()){
                $state.go('index.dashboard');
            }
        }]
    });

In currentUser

    this.resolveLogin = function(){
        var deferred = $q.defer();
        console.log('1')
        $http.get('/profile')
        .success(function(res){
            console.log('2.1')
            root.user = res.data;
            deferred.resolve();
        })
        .error(function(res){
            console.log('2.2')
            deferred.reject();
        });

        // return promise object
        return deferred.promise;
    }

Instead of logging in the order of 1, 2.1, 3 it logs in the order of 1, 3, 2.1.

Answers


Grundy February 2016

You forget return promise from resolve function, so angular should not wait it.

So, if currentUser.resolveLogin(); return promise you should just return it

resolve: {
    data: function(currentUser){
        return currentUser.resolveLogin();
    }
},

Sidenote: $http already return promise, so, you not need create it manually, and can reduce your this.resolveLogin to something like this

this.resolveLogin = function(){
    console.log('1')
    return $http.get('/profile')
    .success(function(res){
        console.log('2.1')
        root.user = res.data;
    })
    .error(function(res){
        console.log('2.2')
    });
}

Post Status

Asked in February 2016
Viewed 3,147 times
Voted 14
Answered 1 times

Search




Leave an answer