How to create an Angular.js $ resource / $ http factory service to process a query string with several parameters from an external resource?

How can I create a factory $ or $ http service to process a query string with several 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 that the user can click to add to the current list of parameters in the query line to get a new list of animals with the desired properties in different combinations. I tried the following, but it does not reload or add new parameters to the existing URL as I wish. Also, I'm not sure if $ route.current.params should be called in a controller or factory, and if this is the best way to do this.

 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:)

+4
source share
1 answer

If the parameters that you pass when you call the resource do not match any of the placeholders specified in the URL, they are automatically converted to query string parameters. Therefore, 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 will be translated into:

 http://thezoo.com/animals?size=med&gender=f 
+10
source

Source: https://habr.com/ru/post/1499212/


All Articles