Search code examples
angularjsngresource

ngResource save() strange behaviour


Can someone please shed some light on this?

var discountResource = $resource(GLOBALS.apiPath + 'discounts/:id');
var discountResponse = discountResource.save($scope.discountForm);

This results in a GET to /discounts

However this results in a POST to /discounts (expected behaviour)

var discountResource = $resource(GLOBALS.apiPath + 'discounts');
var discountResponse = discountResource.save($scope.discountForm);

I'm very stuck on this, as I would like to use the first option, with the placeholder declared. But for the life of me I cannot get it to work.

The reason I want option 1 is so that I can decalre it in a factory and inject the resource into my Controllers. Basically i don't want to redeclare it every time I need an API interaction. I hope that makes sense.


Solution

  • Try something like this

     Module.factory("Discount", ["$resource", function ($resource) { return $resource(GLOBALS.apiPath + "discounts/:Id", { Id: "@Id" }, {
                somthingCustomIfNeeded: { method: 'POST', url: GLOBALS.apiPath + "something-custom" }
            }); }]);
    

    Notice the { Id: "@Id" } object? It tells Angular how to resolve that :Id variable

    Quote from documentation

    If the parameter value is prefixed with @ then the value for that parameter will be extracted from the corresponding property on the data object (provided when calling an action method). For example, if the defaultParam object is {someParam: '@someProp'} then the value of someParam will be data.someProp

    More details here https://docs.angularjs.org/api/ngResource/service/$resource (Search for "paramDefaults")