chrony
chrony

Reputation: 783

How to pass array parameter to AngularJS $resource

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?

Upvotes: 13

Views: 13067

Answers (2)

Shaishab Roy
Shaishab Roy

Reputation: 16805

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}

Upvotes: 23

Kirill Slatin
Kirill Slatin

Reputation: 6143

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

Upvotes: -1

Related Questions