13

When I pass an array to a resource action.. it doesn't convert the array parameter to an array of URL parameters

var Product = $resource('path/products');
Product.query({ids: [1,2,3]})

Instead of getting:

path/products?ids[]=1&ids[]=2ids[]=3

I'm getting:

path/products?ids=1&ids=2ids=3

Anyone knows how to get around this issue?

||||||
22

You can use $resource to pass array

var searchRequest = $resource('/api/search/post', {}, {
    'get': {method: 'GET'}
});
searchRequest.get({'ids[]':[1,2,3]});

then you get request url

/api/search/post?ids%5B%5D=1&ids%5B%5D=2&ids%5B%5D=3

you get %5B%5D instead of []

and if you expect return array instead of object then you should use

'get': {method: 'GET', isArray: true}
||||||
  • 2
    nice, thanks! but why would you label your GET route /post? xD – phil294 Jun 13 '16 at 2:25
  • you saved my life! – Stas Coder Jun 8 '17 at 13:42
-1

Params should be declared like this

var Product = $resource('path/products?:ids',
{ids: '@ids'});

However I am not sure what resulting url you want to achieve. Any of the posted in OP ways is an invalid request, because of repeating parameter.

To stick to GET verb and define an array in query params I see the only way: to construct param as a string

var query = [1,2,3].map(function(el){return 'brand[]='+el}).join('&');
Product.query({ids: query});

PS Unless you have strong reasons the best approach would be to send arrays using POST verb, like described in this post. With array sent over URL you can easily run out of maximum URL length

||||||
  • sorry, what does OP mean? – chrony Apr 1 '15 at 10:53
  • Based on the query, the parameter 'ids' is used to filter the resource.. the parameter can be 'category_id', 'brand_id', etc.. And the parameter can be an array to signify you want to filter the result by these brands for example (e.g: /path/products?brand[]=A&brand[]=B) – chrony Apr 1 '15 at 10:57
  • passing the parameter multiple times without using [] would overwrite the previous parameter passed. such as for the url "/path/products?brand=A&brand=B". the value of brand on the server would be 'B' not an array ['A','B'] because the first parameter brand which holds 'A' gets overwritten by the second brand parameter holding 'B' – chrony Apr 1 '15 at 10:59
  • OP means Original Post or Original Poster based on context – Kirill Slatin Apr 1 '15 at 11:04
  • so does this mean the url "/path/products?brand[]=A&brand[]=B" is not RESTful? – chrony Apr 1 '15 at 11:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.