我需要使用 url 的产品 ID 部分(而不是作为查询参数)从 rest API 获取数据。
工厂:
.factory('Products', ['$resource',
function($resource) {
return $resource('products/:productId', {
productId: '@id'
}, {
query: {
isArray: false
},
update: {
method: 'PUT'
}
});
}
])
Controller :
$scope.getProduct = function(id, from) {
$scope.product = Products.get({ id: id }, function(){
console.log($scope.product);
});
}
我的 url 构造如下:
/products?id=5426ced88b49d2e402402205
代替:
/products/5426ced88b49d2e402402205
有什么想法吗?
最佳答案
当您在 Controller 中调用 Products.get()
时,您没有使用正确的参数名称(根据您对 $资源
)。尝试这样调用它:
Products.get({ productId: id })
这是来自 documentation for $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 中找到“id”作为参数,因此它将其添加到查询字符串中。
关于javascript - AngularJS $resource 将 id 作为查询参数而不是 url 传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26451858/