Search code examples
angularjsangular-resource

AngularJS $resource - POST with id param


I have an angularJS $resource:

$resource("http://localhost:3000/:id",{
   id: '@id'
},
{
   get: {
      method:'GET',
      isArray: false
   },
   foo: {
      method:'POST',
      url: 'http://localhost:3000/:id/foo',
      isArray: false
   }
});

Now if I call:

User.foo({id:'123', anotherParam: 'bar'});

This results in the URL 'http://localhost:3000/foo' being called and passing the id and anotherParam parameters as POST fields.

I actually want it to call 'http://localhost:3000/123/foo' and only pass the anotherParam parameter as a POST field.

How do I get the id parameter to behave correctly?


Solution

  • https://docs.angularjs.org/api/ngResource/service/$resource

    non-GET "class" actions: Resource.action([parameters], postData, [success], [error])

    You need to do:

    User.foo({id:'123', anotherParam: 'bar'}, <post data object>);
    

    When you call the function with a single argument. It assumes that the optional argument is not there and sends it as the postData.