Currently I am using $http.success().error() in my controllers. However, angular has deprecated success/error support and as per style guides the best place to write server $http calls is service.
Given this I would like to know if the following code is the correct way to go forward.
Controller:
var funcWithPromise = function() {
// This service's function returns a promise, but we'll deal with that shortly
TestService.getWeather()
.then(function(data) {
if (data.forecast==='good') {
prepareFishingTrip();
} else {
prepareSundayRoastDinner();
}
}, function(response) {
// promise rejected, could log the error with:
$scope.errorDiv = response.data;
console.log('error', response);
//Manipulate DOM
});
};
Service:
app.factory('TestService', function ($http, $q) {
return {
getWeather: function() {
// the $http API is based on the deferred/promise APIs exposed by the $q service
// so it returns a promise for us by default
return $http.get('http://weather')
.then(function(response) {
return response.data;
}, function(response) {
// something went wrong
return $q.reject(response); //Not sure is it must be response or reponse.data here. With reponse I can utilize response.status.
});
}
};
});