I am currently learning how to use Angular.js and was attempting to write my own authentication code using a REST-like API. Below is the code for my authentication service.
The problem with my signIn
function is that it always returns false, even when my api returns HTTP 200
. After some time, I figured out that it is because of the synchronous nature of javascript that the return response;
statement is executed before the response = res.data.key;
statement.
I don't know how to execute the return statement after the assignment is complete (if the response is HTTP 200
). How do I do this?
angular.module('app').factory('auth', ['Base64', '$http', function(Base64, $http) {
return {
signIn: function(email, password) {
var response = false;
var encoded = Base64.encode(email + ':' + password);
$http.defaults.headers.common.Authorization = 'Basic ' + encoded;
$http.post('api/v1/sign_in', {}).then(function(res) {
if (res.status == 200) {
response = res.data.key;
}
});
return response;
}
}
}]);