I am trying to continue my understanding of promises by writing a login function. The Login function is part of an AuthService that sends an http request to my server and returns a promise (the promise is resolved if the user is verified and rejected if not).
When calling the function in my controller I try to use .success and .error since the function returns a promise but I get the error "Undefined is not a function".
Here is my function that gets the undefined error.
$scope.login = function(email, password) {
return AuthService.login(email, password).success(function(data) {
return console.log("login function returned", data);
}).error((function(data) {
return console.log("There was an error " + data);
}));
};
Here is my Service
.service('AuthService', function($window, $rootScope, $q, $http) {
return {
login: function(email, password) {
var deferred;
deferred = $q.defer();
$http.post('/dashboard/login', {
email: email,
password: password
}).error(function(error, status) {
console.log("Incorrect logi");
return deferred.reject(error);
}).success(function(data, status) {
$window.sessionStorage["userInfo"] = JSON.stringify(data);
return deferred.resolve(data);
});
return deferred.promise;
}
};
});
What confuses me most is that after researching it seems like promises don't have a success or error method but $http is a promise that has that method. Also if they don't have success and error how do you know if something is an error or not? Lastly what is the point of .reject and .resolve if there is no success or error method?