I have a Angularjs resource and in one of the methods, I want to send a query parameter to the backend if that query parameter is non-empty. Is it possible to achieve that without created a different method?
Example resource method:
get: {
method: 'GET',
url: /api/:token?source=:source,
paramSerializer: someSerializer
},
The code to call the method is,
myResource.get({token: '1234'}, {source: <some source>});
The token is required, but the source is optional, so sometimes it is not passed in to the call above. So if a value is provided for the source, I want to be able to send the source. If the source value is not provided, I want to not send the source at all. For instance, the call will become /api/1234 if source is empty, and the call will become /api/1234?source=some_source if the source is set as some_source.
With the code above, if the source is empty, I see that the request is '/api/1234?source=' when the source is empty.
Simply define the url template without the extra parameters:
get: {
method: 'GET',
url: "/api/:token",
},
Then add the extra parameters when invoking the action:
myResource.get({token: '1234', source: <some source>});
The extra parameters will be automatically added to the url as query parameters.
From the Docs:
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
?
.
For more information, see