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?

2 Answers 2

23

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}
Sign up to request clarification or add additional context in comments.

2 Comments

nice, thanks! but why would you label your GET route /post? xD
you saved my life!
-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

8 Comments

sorry, what does OP mean?
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)
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'
OP means Original Post or Original Poster based on context
so does this mean the url "/path/products?brand[]=A&brand[]=B" is not RESTful?
|

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.