Search code examples
angularjsapirestcrudngresource

Including placeholder changes ngResource save() method from POST to GET


a really simple example. I have a RESTful api and I setup my resource the following way.

app.factory('apiFactory' , ['$resource', 'GLOBALS', 
    function($resource, GLOBALS){
        return {
            Discounts: $resource(GLOBALS.apiPath + 'discounts/:id', {id:'@id'}, {update:{method: 'PUT'}})
        }     
    }
])

And then I call it in a Controller like so

var discountResponse = apiFactory.Discounts.save($scope.discount);

Everything works fine until I add '/:id' to my URL. I do this so that my delete method passes the id along. Like so 'discounts/6'.

The issue that I have is that as soon as I add the placeholder my save() method sends off a GET instead of a POST.

Request URL:http://local:8089/api/discounts
Request Method:GET
Status Code:200 OK

If I remove the placeholder I get

Request URL:http://local:8089/api/discounts
Request Method:POST
Status Code:200 OK

And everything works great, accept for the delete request, which now does not map the placeholder, as it no longer exists.

I have absolutely no idea why. I'm pretty new to $resource, so I am very sure I am not understanding something.


Solution

  • The answer was provided on a differently formulated question and I thought I'd share it.

    return {
            Discounts: $resource(GLOBALS.apiPath + 'discounts/:id', {id:'@id'} ,{
                save: { 
                    method: 'POST', url: GLOBALS.apiPath + "discounts" 
                },
                update: {
                    method: 'PUT', url: GLOBALS.apiPath + "discounts/:id" 
                }
            })
        }
    

    It would seem that for the save() to POST properly I had to define a path in the customConfig object. I'm not sure why this didn't work for me out of the box.

    The answer was provided here. Many Thanks!
    ngResource save() strange behaviour