Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 630
richwol Avatar asked Jul 29 '15 13:07

richwol


2 Answers

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.

like image 74
dting Avatar answered Oct 18 '22 21:10

dting


The accepted solution didn't work for me (AngularJS v1.4.8). Have to manually set content type and transform to form data.

Sample:

var DirectoryApi = $resource('api/directories', null, {
    move: {
        url: 'api/directories/:name/_move',
        params: {"name" : "@name"},
        headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
        transformRequest: function (param) {
            return $.param(param);
        },
        method: 'POST'
    },
});

And usage:

function moveDirectory(name, parent, after) {
    return DirectoryApi.move({name: name}, {parent: parent, after: after});
}
like image 1
marknorkin Avatar answered Oct 18 '22 22:10

marknorkin