ngResource save() 奇怪的行为
ngResource save() strange behaviour
有人可以解释一下吗?
var discountResource = $resource(GLOBALS.apiPath + 'discounts/:id');
var discountResponse = discountResource.save($scope.discountForm);
这导致 GET 到 /discounts
然而,这会导致 POST 到 /discounts(预期行为)
var discountResource = $resource(GLOBALS.apiPath + 'discounts');
var discountResponse = discountResource.save($scope.discountForm);
我非常坚持这一点,因为我想使用第一个选项,并声明占位符。但是对于我的一生,我无法让它发挥作用。
我想要选项 1 的原因是我可以在工厂中对其进行贴标并将资源注入到我的控制器中。基本上我不想每次需要 API 交互时都重新声明它。我希望这是有道理的。
尝试这样的事情
Module.factory("Discount", ["$resource", function ($resource) { return $resource(GLOBALS.apiPath + "discounts/:Id", { Id: "@Id" }, {
somthingCustomIfNeeded: { method: 'POST', url: GLOBALS.apiPath + "something-custom" }
}); }]);
注意到 { Id: "@Id" }
对象了吗?它告诉 Angular 如何解析 :Id 变量
引自文档
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
此处有更多详细信息https://docs.angularjs.org/api/ngResource/service/$resource
(搜索 "paramDefaults")
有人可以解释一下吗?
var discountResource = $resource(GLOBALS.apiPath + 'discounts/:id');
var discountResponse = discountResource.save($scope.discountForm);
这导致 GET 到 /discounts
然而,这会导致 POST 到 /discounts(预期行为)
var discountResource = $resource(GLOBALS.apiPath + 'discounts');
var discountResponse = discountResource.save($scope.discountForm);
我非常坚持这一点,因为我想使用第一个选项,并声明占位符。但是对于我的一生,我无法让它发挥作用。
我想要选项 1 的原因是我可以在工厂中对其进行贴标并将资源注入到我的控制器中。基本上我不想每次需要 API 交互时都重新声明它。我希望这是有道理的。
尝试这样的事情
Module.factory("Discount", ["$resource", function ($resource) { return $resource(GLOBALS.apiPath + "discounts/:Id", { Id: "@Id" }, {
somthingCustomIfNeeded: { method: 'POST', url: GLOBALS.apiPath + "something-custom" }
}); }]);
注意到 { Id: "@Id" }
对象了吗?它告诉 Angular 如何解析 :Id 变量
引自文档
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
此处有更多详细信息https://docs.angularjs.org/api/ngResource/service/$resource (搜索 "paramDefaults")