4

How could a factory $resource or $http service be created to handle a query string with multiple arbitrary parameters from an external resource? eg.

#/animals
#/animals?gender=m
#/animals?color=black
#/animals?size=small
#/animals?gender=m&color=black
#/animals?size=med&gender=f
#/animals?size=lg&gender=m&color=red

The idea is that there are buttons/inputs which the user can press to add to the current list of parameters in the query string to get a new list of animals with the desired properties in different combinations. I have tried the following but it doesn't reload or add new parameters to the existing url as desired. Also, I'm not sure if $route.current.params should be called in the controller or the factory and if that's the best way to do it.

angular.module(Animals, ['$resource', '$route', '$location', function($resource, $route, $location) {
  return $resource('http://thezoo.com/animals', $route.current.params, { query: {method: 'GET', isArray: true}});
}]);

Thanks :)

1 Answer 1

10

If the parameters you pass in when you call the resource don't match any of the placeholders specified in the url, they're automatically converted to query string params. So you should do something like:

angular.module(Animals, ['$resource', '$route', '$location', function($resource, $route, $location) {
  return $resource('http://thezoo.com/animals', { query: {method: 'GET', isArray: true}});
}]);

and then when you try to use it, you can do:

Animals.query({size:"med",gender:'f'});

and it'll get translated to:

http://thezoo.com/animals?size=med&gender=f
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you - I believe this will work great! Of course, it looks so obvious now that you've showed how. I posted a follow up question here :
i think {size="med",gender='f'} is wrong. {size : "med", gender:"f"} is the correct format, isn't it??.
Isn't there a missing argument there? I think it should be return $resource('http://thezoo.com/animals', {}, { query: {method: 'GET', isArray: true}}); (notice the extra empty object)

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.