问题描述
下面是在服务我的code。
Here's my code in the service.
this.loginUser = function(checkUser) {
Parse.User.logIn(checkUser.username, checkUser.password, {
success: function(user) {
$rootScope.$apply(function (){
$rootScope.currentUser = user;
});
}
});
};
下面是我的code控制器:
Here's my code in the controller:
$scope.logIn = function(){
authenticationService.loginUser($scope.checkUser);
console.log($scope.currentUser)
};
所以,我想要做的是,执行一些code完成AJAX调用的,其成功函数设置$ scope.currentUser,的值,我可以用一些条件逻辑(如重定向等后)成功的功能正确设置值,但的console.log
应执行后执行authenticationService.loginUser()
功能。
So, what I want to do is, execute some code AFTER the completion of AJAX call, whose success function sets the value of $scope.currentUser, which, I can use for some conditional logic (like redirecting etc)The success function is correctly setting the value, but the console.log
should be executed AFTER the execution of authenticationService.loginUser()
function.
推荐答案
您需要返回使用一个承诺 $ q 和行动上。
You need to return a promise using $q and act on that.
例如,在你的服务:
this.loginUser = function(checkUser) {
var deferred = $q.defer();
Parse.User.logIn(checkUser.username, checkUser.password, {
success: function(user) {
$rootScope.$apply(function (){
$rootScope.currentUser = user;
});
deferred.resolve();
}
});
return deferred.promise;
};
然后在上的成功,控制器的行为:
Then in your controller act on the success:
$scope.logIn = function(){
authenticationService.loginUser($scope.checkUser).then(function() {
console.log($rootScope.currentUser));
});
};
这篇关于AngularJS:如何执行控制器功能AJAX调用的服务完成后?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!