Reputation: 17
Im trying to catch errors returned from my server and return them at the end of a login function. If it succeeds, no errors will be returned and if it fails the list of errors will be returned. The login code is part of an AngularJS service as below:
angular.module('auth').service('RestfulAuthService',['$http','REST_BASE_URL',function($http,base_url){
var self = this;
//define backend urls
var api_urls = {
login: base_url+'/login/',
}
//hold user credentials to be accessed
var api_user = {
username:null,
email:null,
first_name:null,
last_name:null,
}
var api_user_token = null;
self.user_profile = function(){
return api_user;
}
self.login = function(username,password){
var errors = {none:null};
$http.post(api_urls.login,{username:username,password:password})
.then(function(response){ //success
//extract data
api_user.username = response.data.username;
api_user.email = response.data.email;
api_user.first_name = response.data.first_name;
api_user.last_name = response.data.last_name;
api_user_token = response.data.token;
//Add auth token to headers for all future requests
$http.defaults.headers.common['Authorization'] = api_user_token;
errors = {};
},function(response){ //error
errors = response.data; //return serializer errors
});
return errors;
};
//REST OF SERVICE ...
The value returned however is always {none:null}. In other words, the errors variable hasnt been changed by the success or failure functions. I'm pretty sure this is a scoping issue, but I don't know how to fix it.
Upvotes: 0
Views: 48
Reputation: 1251
It is a scoping issue, but it is more so a synchronization issue. The HTTP request starts and return errors;
is executed long before any of the .then
code is reached. You have to use a callback to pass the error data.
self.login = function(username,password,callback){
var errors = {none:null};
$http.post(api_urls.login,{username:username,password:password})
.then(function(response){ //success
//extract data
api_user.username = response.data.username;
api_user.email = response.data.email;
api_user.first_name = response.data.first_name;
api_user.last_name = response.data.last_name;
api_user_token = response.data.token;
//Add auth token to headers for all future requests
$http.defaults.headers.common['Authorization'] = api_user_token;
errors = {};
callback(errors);
},function(response){ //error
errors = response.data; //return serializer errors
callback(errors);
});
};
The calling code must call with the callback, and use its argument to access the errors.
self.login(username, password, function(errors) {
// handle errors
});
Upvotes: 2