Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute:

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?

share|improve this question

2 Answers 2

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}
share|improve this answer

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

share|improve this answer
    
sorry, what does OP mean? – Jasper Apr 1 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) – Jasper Apr 1 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' – Jasper Apr 1 at 10:59
    
OP means Original Post or Original Poster based on context – Kirill Slatin Apr 1 at 11:04
    
so does this mean the url "/path/products?brand[]=A&brand[]=B" is not RESTful? – Jasper Apr 1 at 11:06

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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