ngResource save() strange behaviour

喜欢而已 提交于 2019-12-12 04:03:24

问题


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.


回答1:


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")



来源:https://stackoverflow.com/questions/31114860/ngresource-save-strange-behaviour

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!