javascript - AngularJS $resource 将 id 作为查询参数而不是 url 传递

标签 javascript angularjs angular-resource

我需要使用 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/

相关文章:

javascript - 如何在javascript中过滤对象数组?

javascript - Angular img src 控制台错误

angularjs - 如何取消 $resource 请求

angularjs - 如何配置 Angular $resource (ngResource) 以使用 CORS 从另一个域中提取数据

javascript - 当我更改任何选择时,指令不监听 $watch

angularjs - 保存后项目消失

javascript - 是否可以将 div 中的随机内容克隆到另一个页面?

javascript - 处理 dom 之前的浏览器 native 点击 :loaded

javascript - 文件更改时避免自动重启服务器 meteor

javascript - 在 Rails 应用程序的移动尺寸屏幕中将图像导航元素对齐为 2 行