Search code examples
angularjsangular-resourceangular-promise

AngularJS hide promises while using $resource


I have a simple RESTful service like the following:

services.factory('UserService', ['$resource, function() {
   return $resource('...');
}]);

This way I have to invoke like this:

UserService.get({id: userId}, function(response) {
 // do something.
});

I wanted to be able to do something like this:

UserService.get(userId).then(function(response) {
    // do something with data
});

Is it possible? I am struggling with this and end up always having to use $promise.then() in my controllers. I wanted to "hide" that $promise in my RESTful service.


Solution

  • $resource purposely exposes the promise through ... well ... $promise, so you can use the UserService to abstract this:

    services.factory("UserService", ["$resource", function ($resource) {
        var userService = $resource("...");
    
        return {
            get: function (id) {
                return userService.get({id: id}).$promise;
            }
        }
    });