简体   繁体   中英

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.

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')
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM