Search code examples
angularjsangular-resource

When do we use .$put instead of .put on an angular resource?


Say, I have the following resource:

angular.module('app.resources.demo-resource', ['ngResource'])
.service('demoResource',
  function ($resource) {
    return $resource('/api/path', { }, { put: { method: 'PUT' } });
  });

and I want to invoke the put request, using promises later. How do I do it correctly?

newResource.$put().then(...) or newResource.put().then(...)?
Does both variants exist and what is the difference between them?


Solution

  • When you define a "non-GET" action (basically, one with a method that has a request body: PUT, POST, PATCH), ngResource will automatically create corresponding actions/methods on every instance of that resource (prefixed by $). This is just for convenience.

    Basically, you have two ways to call such an action:

    <Resource>.action([parameters], postData, [success], [error])
    

    or

    <instance>.$action([parameters], [success], [error])
    

    The benefit of the latter is that you don't need to specify the postData (it's the <instance> object that acts as the data).