Javascript AngularJS $resource 将 id 作为查询参数传递给 url
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26451858/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
AngularJS $resource passes id as query parameter instead in url
提问by orszaczky
I need to GET data from a rest API, with the product id part of the url (and not as query parameter).
我需要使用 url 的产品 id 部分(而不是作为查询参数)从 rest API 获取数据。
The factory:
工厂:
.factory('Products', ['$resource',
function($resource) {
return $resource('products/:productId', {
productId: '@id'
}, {
query: {
isArray: false
},
update: {
method: 'PUT'
}
});
}
])
The controller:
控制器:
$scope.getProduct = function(id, from) {
$scope.product = Products.get({ id: id }, function(){
console.log($scope.product);
});
}
My url is constructed like:
我的网址构造如下:
/products?id=5426ced88b49d2e402402205
instead of:
代替:
/products/5426ced88b49d2e402402205
Any ideas why?
任何想法为什么?
回答by Sunil D.
When you call Products.get()in the controller, you are not using the correct parameter name (you need to use "productId" instead of "id" based on your definition of the $resource). Try calling it like this instead:
当您Products.get()在控制器中调用时,您没有使用正确的参数名称(根据您对 的定义,您需要使用“productId”而不是“id” $resource)。试着这样称呼它:
Products.get({ productId: id })
Here is a snippet from the documentation for $resourcewhich explains how it works:
这是文档中的$resource一个片段,解释了它是如何工作的:
Each key value in the parameter object is first bound to url template if present and then any excess keys are appended to the url search query after the ?.
参数对象中的每个键值首先绑定到 url 模板(如果存在),然后将任何多余的键附加到 ? 之后的 url 搜索查询。
In your case, it's not finding "id" as a parameter in the URL, so it adds that to the query string.
在您的情况下,它没有在 URL 中找到“id”作为参数,因此它将其添加到查询字符串中。

