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?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.