Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS $resource passes id as query parameter instead in url

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?

like image 505
orszaczky Avatar asked Oct 19 '14 15:10

orszaczky


People also ask

Can I pass URL as query parameter?

Yes, that's what you should be doing. encodeURIComponent is the correct way to encode a text value for putting in part of a query string. but when it is decoded at the server, the parameters of url are interpreted as seperate parameters and not as part of the single url parameter.

How do I change the URL of a query parameter?

The value of a parameter can be updated with the set() method of URLSearchParams object. After setting the new value you can get the new query string with the toString() method. This query string can be set as the new value of the search property of the URL object.

What is URL query parameter?

Query parameters are a defined set of parameters attached to the end of a url. They are extensions of the URL that are used to help define specific content or actions based on the data being passed.

What do you call a parameter added to the URL?

URL parameters (known also as “query strings” or “URL query parameters”) are elements inserted in your URLs to help you filter and organize content or track information on your website.


1 Answers

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.

like image 94
Sunil D. Avatar answered Oct 10 '22 23:10

Sunil D.