There is related question about processing $http in a service, but I wanted to elaborate slightly. I would like my controller to be able to execute service calls using API similar to the Angular $http API:
$scope.login = function(user) {
securityService.login(user).success(function(data) {
$scope.data = data;
}).error(function(data) {
$scope.error = data;
});
};
That's a nice readable API. On the surface, all I would need to do in the service API is:
return {
name : 'User Service',
login : function(user) {
return $http.post("/api/login", user);
}
};
Great, it returns the promise and the success
and error
messages come with. But... What if I want to deal with the success and failure cases in the service? I want to maintain the nice, readable service API. In this case, maybe I'd want to preserve the user so that I could expose methods like securityService.currentUser()
or `securityService.isLoggedIn()'.
I tried the $http.post().then(...)
promise API, but those return the entire HTTP response. Again, I want to isolate HTTP to the services and maintain a similar concrete callback API.