Search code examples
javascriptangularjspromiseangular-resource

Getting a promise back from an Angular Resource


I'm using $resource to do some basic CRUD stuff in Angular but I don't think I understand how to use the different resource methods.

As far as I can tell, the "regular" methods - save(), get() etc happen synchronously, and you can pass in a callback function to run on completion if you want to do "classic" JS async calls. The result of each also has a $promise property which returns a promise, if you want to do async that way (I do!).

But there are also $ versions of all the methods except (for reasons I also don't understand) get() and query(). Are these $ methods a shortcut for .$promise? If so, why is there no $get() or $query()?


Solution

  • Yeah, the docs of ngResource are very hard to understand. Basically you need to differentiate between

    • class actions (methods of $resource) and
    • instance actions (methods of instances of $resource)

    class actions like

    var User = $resource('/user/:userId', {userId:'@id'});
    User.get({userId:123}, function(user) {
      user.abc = true;
      user.$save();
    });
    

    have an additional property $promise that is resolved when the data is returned from the $http request. Thats why this can be written as:

    User.get({userId:123})
        .$promise.then(function(user) {
          $scope.user = user;
        });
    

    from the docs:

    When the data is returned from the server then the object is an instance of the resource class. The actions save, remove and delete are available on it as methods with the $ prefix. This allows you to easily perform CRUD operations (create, read, update, delete) on server-side data like this:

    That's why user.$save(); can be invoked on the instance in the example above.