I have setup an authentication service which I inject into my Login controller I then call it to do a login... for example
$scope.login = function() {
var loginResult = authentication.login($scope.model.user, $scope.model.pass);
I need to know weather the login was successful or not as I need to peform some logic depending on the result. I could return a bool from login on the authentication service but the problem is that inside my login it calls to a rest service which has a promise. like so
return {
authenticate: function (username, password) {
var enc = base64.encode(username + ':' + password);
AuthRestangular.setDefaultHeaders({'Authorization': 'Basic ' + enc });
AuthRestangular.one('login').get().then(function (data) {
isLoggedIn = true;
return true;
}, function () {
return false;
});
So it takes a few seconds for the Rest service to return and it returns a promise i.e. then .... either true or false. So the service actually returns to the Login Controller before I have the promise.
So I am confused what i should do here, Can i have my service also return a promise?? otherewise the loginResult is always false as it doesn't return in time hence the default for my bool is false.
Any ideas
Thanks
You should not return true false from service instead you should return a promise from the service and use that promise inside controller
--service
return {
authenticate: function (username, password) {
var enc = base64.encode(username + ':' + password);
AuthRestangular.setDefaultHeaders({'Authorization': 'Basic ' + enc });
return AuthRestangular.one('login').get();
});
--controller
authentication.login($scope.model.user, $scope.model.pass).then(function(data){})