Reputation: 941
I an new to angular and I am wondering what is the best practice for the .success
and .error
functions to be placed, within the controller or within the factory? example:
do I use this:
(function(){
'use strict';
angular
.factory('apiService', function($http){
var apiService = {
getProfileData: getProfileData
}
return apiService;
function getProfileData(url){
return $http.jsonp(url);
}
});
})();
or this:
(function(){
'use strict';
angular
.factory('apiService', function($http){
var apiService = {
getProfileData: getProfileData
}
return apiService;
function getProfileData(url){
return $http.jsonp(url)
.success(function(data){
return data;
})
.error(function(err){
return err;
});
}
});
})();
and how should I be handling this in a controller?
Upvotes: 0
Views: 1719
Reputation: 559
You should choose 2nd option, but .success
return a promise but offeres slightly more convienient syntax, where as .then
is full power of the promise API but slightly more verbose, so despite of using .success i suggest you to prefer .then
.
Upvotes: 0
Reputation: 136164
Both the approaches are correct, but depends on how you wanted to expose the API.
1st approach
It is pretty simple. You should go for this approach only if you are giving whole control over all the aspect available in the $http
response like data, header, status & config
2nd approach
By using this approach you could create an abstraction layer between your callee
method & service, It would return data from the service, other part of response would hidden for the callee
method.Also here you could do some data manipulation operation Some times you could also validation before returning a data & you could resolve or reject promise based on condition.
I'd suggest you to go for 2nd approach so that you could get more access on data before returning it to callee method.
Upvotes: 0
Reputation: 483
I would advise having it in the service/factory. Controller doesn't need to know about the communication implementation (which you might want to mock in the future).
Separation of concerns. :)
Upvotes: 0
Reputation: 6676
You should definitely choose the 2nd option you posted and handle it in the service. Services are meant to be reusable, so if error handling is not done in there, it will have to be done in every single controller that consumes it.
EDIT: The exception to this rule would be if the error and success handling would be done completely different depending on the controller that consumes the service, but I have never found this to be the case for me.
Upvotes: 3