AngularJS $resource passes id as query parameter instead in url
Asked Answered
R

1

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?

Ranson answered 19/10, 2014 at 15:4 Comment(0)
N
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.

Nexus answered 19/10, 2014 at 16:45 Comment(2)
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.Alec
@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)Nexus

© 2022 - 2024 — McMap. All rights reserved.