1

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.

2 Answers 2

1

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

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

Comments

1

If you pass query params via get.params{} then AngularJS will automatically handled stripping out undefined properties.

1 Comment

Thank you. I am not very familiar with this. If you could please tell me how to modify the myResource.get({token: '1234'}, {source: <some source>}); call, that would help. I will research as well, thanks again.

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.