30

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?

orszaczky
  • 13,301
  • 8
  • 47
  • 54

1 Answers1

57

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.

Sunil D.
  • 17,983
  • 6
  • 53
  • 65
  • 7
    So what is the purpose of the `@` prefixed value then? "If the parameter value is prefixed with @ then the value for that parameter will be extracted from the corresponding property on the `data` object (provided when calling an action method). For example, if the `defaultParam` object is `{someParam: '@someProp'}` then the value of `someParam` will be `data.someProp`." Sounds like you should be able to pass in an `id` value and the resource would use it to populate the `productId` param. But this is not the case. – Erik J Nov 13 '15 at 21:42
  • Thank you! Helped me today! – Tabetha Moe Jan 13 '16 at 21:14
  • 2
    @Erik J This is a little late, but I think the @ prefixed value is only useful when your using an instance of a `$resource`, as opposed to using the resource class itself. The class methods of the resource (eg: `Products.get(productId: xx)`) do not have an object to extract the ID from. But if you had an instance of a product resource, it would extract the @ value from the object and insert it in the URL (eg: myProductResource.save() would post to /products/:productId) – Sunil D. Jul 28 '16 at 10:03