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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With