Search code examples
angularjsangular-resource

How to pass a query string in the URL with PUT or POST on an array?


I am trying to make an update on a list of elements using an angular $resource service:

.factory('Elements', ['$resource', function($resource) {
    return $resource('../api/:type/:id', 
        {   type:'@type', id:'@id' }, 
        {   update: { method: 'PUT' }, 
            updateList: { method: 'PUT', isArray: true }
        });
    }])

1 inside the controller, this function updates a single object:

element.update({ 'name': name, 'value': value }); 

It sends an HTTP PUT request to the server with this url: /api/theType/theId?name=theName&value=theValue. This is working fine.

2 Now, instead of a single object, this function updates an array of objects, using the updateList method:

elements.updateList({ 'name': name, 'value': value }); 

the problem:

In this case, the requested URL is /api/theType. But why the query string (name=theName&value=theValue) is not here anymore?

How to pass a query string in the URL when updating an array with PUT?


Solution

  • Both calls are probably broken, and you don't know it. In the current state, you're just updating the server with the parameters object instead of the real data.

    When passing a single object on non-GET actions, it's passed as the data for update. From the docs:

    The action methods on the class object or instance object can be invoked with the following parameters:

    ...

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

    So it is just a misuse of the action method. Send the data object for update after the action parameters, and you're good to go:

    element.update({ 'name': name, 'value': value }, dataObject);
    

    Source

    $resource on the AngularJS docs