AngularJS $resource - POST with id 参数
AngularJS $resource - POST with id param
我有一个 angularJS $资源:
$resource("http://localhost:3000/:id",{
id: '@id'
},
{
get: {
method:'GET',
isArray: false
},
foo: {
method:'POST',
url: 'http://localhost:3000/:id/foo',
isArray: false
}
});
现在如果我打电话:
User.foo({id:'123', anotherParam: 'bar'});
这导致调用 URL 'http://localhost:3000/foo' 并将 id 和 anotherParam 参数作为 POST 字段传递。
我实际上希望它调用“http://localhost:3000/123/foo”并且仅将 anotherParam 参数作为 POST 字段传递。
如何让 id 参数正确运行?
https://docs.angularjs.org/api/ngResource/service/$resource
non-GET "class" actions: Resource.action([parameters], postData, [success], [error])
您需要做的:
User.foo({id:'123', anotherParam: 'bar'}, <post data object>);
当您使用单个参数调用函数时。它假定可选参数不存在并将其作为 postData 发送。
接受的解决方案对我不起作用 (AngularJS v1.4.8
)。
必须手动设置内容类型并转换为表单数据。
样本:
var DirectoryApi = $resource('api/directories', null, {
move: {
url: 'api/directories/:name/_move',
params: {"name" : "@name"},
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
transformRequest: function (param) {
return $.param(param);
},
method: 'POST'
},
});
和用法:
function moveDirectory(name, parent, after) {
return DirectoryApi.move({name: name}, {parent: parent, after: after});
}
我有一个 angularJS $资源:
$resource("http://localhost:3000/:id",{
id: '@id'
},
{
get: {
method:'GET',
isArray: false
},
foo: {
method:'POST',
url: 'http://localhost:3000/:id/foo',
isArray: false
}
});
现在如果我打电话:
User.foo({id:'123', anotherParam: 'bar'});
这导致调用 URL 'http://localhost:3000/foo' 并将 id 和 anotherParam 参数作为 POST 字段传递。
我实际上希望它调用“http://localhost:3000/123/foo”并且仅将 anotherParam 参数作为 POST 字段传递。
如何让 id 参数正确运行?
https://docs.angularjs.org/api/ngResource/service/$resource
non-GET "class" actions: Resource.action([parameters], postData, [success], [error])
您需要做的:
User.foo({id:'123', anotherParam: 'bar'}, <post data object>);
当您使用单个参数调用函数时。它假定可选参数不存在并将其作为 postData 发送。
接受的解决方案对我不起作用 (AngularJS v1.4.8
)。
必须手动设置内容类型并转换为表单数据。
样本:
var DirectoryApi = $resource('api/directories', null, {
move: {
url: 'api/directories/:name/_move',
params: {"name" : "@name"},
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
transformRequest: function (param) {
return $.param(param);
},
method: 'POST'
},
});
和用法:
function moveDirectory(name, parent, after) {
return DirectoryApi.move({name: name}, {parent: parent, after: after});
}