javascript - Controller doesn't wait for resolve -
i have resolve, controller seems run before 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 order of 1, 2.1, 3 logs in order of 1, 3, 2.1.
you forget return promise resolve function, angular should not wait it.
so, if currentuser.resolvelogin();
return promise should return it
resolve: { data: function(currentuser){ return currentuser.resolvelogin(); } },
sidenote: $http
return promise, so, not need create manually, , can reduce this.resolvelogin
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') }); }
Comments
Post a Comment