Reputation: 8204
I recall seeing many times on stack overflow the recommendation to delegate angular $http calls to services rather than doing it in controllers. I can see the cleanliness of doing that when one wants the service to modify the response object in some way, before passing it back to the controller.
However, what if there is no need to modify the response? It seems redundant to use a function in the controller to call a service to return a $http request in this case. Is there some other reason I could know about to reserve $http calls for services rather than controllers?
e.g.
// in controller
function potatoChipTime() {
chip = chipService.getAPotatoChip();
}
// in service (inject $q and $http)
var service = {
getAPotatoChip: getAPotatoChip
}
return service;
function getAPotatoChip() {
var deferred = $q.defer();
$http.get(url)
.success(function(response) {
deferred.resolve(response);
)}.error(function(error) {
deferred.reject(error)
});
return deferred.promise;
}
// redundant, no? a lot of fuss to get a potato chip?
Upvotes: 0
Views: 70
Reputation: 692161
I agree with you. I generally only put such code in a service if the service is reused in several controllers and if it does more than simply make an HTTP request.
Note that your service code doesn't leverage promise chaining and thus uses a promise anti-pattern. All you would need is
function getAPotatoChip() {
return $http.get(url).then(function(response) {
return response.data;
}).catch(function(response) {
return $q.reject(response.data);
});
}
or, if you don't really care whether the promise is rejected with the data or with the complete response in case of error:
function getAPotatoChip() {
return $http.get(url).then(function(response) {
return response.data;
});
}
Upvotes: 0