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;
});
}
});
};
Here's my code in the controller:
$scope.logIn = function(){
authenticationService.loginUser($scope.checkUser);
console.log($scope.currentUser)
};
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.
Call function after ajax complete You can simply copy/paste code in the body tag of the html page and reload page to get the content form https://api.joind.in/v2.1/talks/10889 URL after success and call callFunctionAfterAjaxCallComplete() function after ajax request is completed.
The AngularJS provides a control service named as AJAX – $http, which serves the task for reading all the data that is available on the remote servers. The demand for the requirement of desired records gets met when the server makes the database call by using the browser. The data is mostly needed in JSON format.
All the AngularJS application mainly relies on the controllers to control the flow of data in that application. Basically, it controls the data of AngularJS applications and the controller is a Javascript object, created by a standard JavaScript object constructor.
In AngularJS, a Controller is defined by a JavaScript constructor function that is used to augment the AngularJS Scope. Controllers can be attached to the DOM in different ways.
You need to return a promise using $q and act on that.
For instance in your service:
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));
});
};
Try using $rootScope.$broadcast
in your service then listen for it in your controller:
Service
Parse.User.logIn(checkUser.username, checkUser.password, {
success: function(user) {
$rootScope.$apply(function (){
$rootScope.currentUser = user;
$rootScope.$broadcast('user.online');
});
}
});
Controller
$scope.$on('user.online',function(){
[ DO STUFF HERE ]
});
This isn't the best way to do this though @comradburk's use of $q is probably a better way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With