I have the following code that calls an REST webservice. The web service returns a boolean
.
checkCurrentPassword: function (passwordInfo) {
var valid = false;
$http.post('/api/preference/password/check', passwordInfo)
.success(function (data) {
valid = data;
});
return valid;
}
The trouble is that by the time the checkCurrentPassword
returns valid
is still false
because the ajax call has not completed due to its asynchronous nature.
I am not sure how to make sure the valid
variable is properly assigned the value returned from the server.
Can anyone please help?
edit 1:
Using a callback, It seems I am only deporting the problem to the controller layer... See below:
from angular service:
checkCurrentPassword: function (passwordInfo, callback) {
return $http.post('/api/preference/password/check', passwordInfo)
.success(function (data) {
callback(data);
});
}
from angular controller:
$scope.updatePassword = function () {
if ($scope.updatePasswordForm.$valid) {
var valid = false;
passwordService.checkCurrentPassword({plainPassword: $scope.passwordInfo.currentPassword}, function(data, status){
valid = data;
});
console.log(valid);//always false
passwordService.updatePassword($scope.passwordInfo, function (data, status) {
console.log('Updated password successfully');
$state.go('dashboard');
});
}
};
edit 2: here is how I rewrote the controller:
$scope.updatePassword = function () {
if ($scope.updatePasswordForm.$valid) {
passwordService.checkCurrentPassword({plainPassword: $scope.passwordInfo.currentPassword}).success(function (data) {
if (data) {
passwordService.updatePassword($scope.passwordInfo, function (data, status) {
console.log('Updated password successfully');
$state.go('dashboard');
});
}
});
}
};