AngularJS $resource - POST with id param
Asked Answered
C

2

12

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?

Calpac answered 29/7, 2015 at 13:50 Comment(0)
G
23

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.

Godliman answered 29/7, 2015 at 14:6 Comment(0)
F
1

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});
}
Forelock answered 31/3, 2017 at 9:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.