I am creating a simplified wrapper around $http for our REST API, aiming to return a promise in a similar fashion as $http does (after data manipulation).
Here is the service I have set up:
Services.service('Item', ['$http', '$q', function($http, $q){
var deferred = $q.defer();
var getSuccess = function(data, status, headers, config){
var item = angular.copy(data);
item.primaryImage = 'https://my.cdn.com/' + item.meta.images[0].s3id;
if(item.meta.source_link !== null) {
item.sourceLink = item.meta.source_link.url;
}
deferred.resolve(item, data, status, headers, config);
};
var getError = function(data, status, headers, config) {
deferred.reject(data, status, headers, config);
};
this.get = function(userID, itemID) {
$http({
method: 'GET',
url: '/api/items/' + userID + '/' + itemID
}).success(getSuccess).error(getError);
return deferred.promise;
};
}]);
However, based on my understanding of the documentation, it seems that I need to utilize .then(success, error, always)
instead of .success().error().always()
like how $http
works.
Is there a way to implement promises in a similar manner to $http
? That would be very convenient.
var req = Item.get($routeParams.userID, $routeParams.itemID);
req.success(function(item){
window.console.log('Received item:', item);
});
.error(function(item){
window.console.log('Oops. It failed.')
})