AngularJS $resource passes id as query parameter instead in url

orszaczky picture orszaczky · Oct 19, 2014 · Viewed 36.1k times · Source

I need to GET data from a rest API, with the product id part of the url (and not as query parameter).

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?

Answer

Sunil D. picture Sunil D. · Oct 19, 2014

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 })

Here is a snippet from the documentation for $resource which explains how it works:

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 ?.

In your case, it's not finding "id" as a parameter in the URL, so it adds that to the query string.