adamdport February 2016

$http.get doesn't work with arrays with only one element. How do I specify the param type?

I'm using Angular's $http.get() method to query my API:

var arr = ['foo','bar'];
return $http.get("api/foo", {
  params: { sampleids: arr}
});

This results in a request to /api/foo?sampleids=115&sampleids=116 which works ok. If I reduce the size of the array to a single element, however, it becomes /api/foo?sampleids=115, which express (node.js) fails to interpret as an array.

If Angular sent the query as /api/foo?sampleids[]=115 instead, it should work fine. Is there any way I can tell it to do that?

Answers


Joe Clay February 2016

You can use the paramSerializer property in your request config to customize how the parameters object gets converted to a string.

return $http.get("api/foo", {
  params: { myArray: arr},
  paramSerializer: function (params) {
      // Return a string...
  }
});

You can look at the default implementation here, if you're not sure how to go about serializing the object: https://github.com/angular/angular.js/blob/master/src/ng/http.js#L27.

Additionally, if you provide a string rather than a function, it will look for a service with that name - this could be helpful if you want to reuse it. There's a $httpParamSerializerJQLike service provided by default, which serializes them in the same format as jQuery's param() function.


sjokkogutten February 2016

There seems to be some uncertainty how to best implement arrays as parameters.
You could try using JSON.stringify:

var arr = ['foo','bar'];
$http(
  method: 'GET',
  url: 'api/foo',
  params: {
    arr: JSON.stringify(arr) 
})

Or simply:

var arr = ['foo','bar'];
$http(
  method: 'GET',
  url: 'api/foo',
  params: {
    "arr[]": arr
})

You might find this SO article useful

Post Status

Asked in February 2016
Viewed 1,740 times
Voted 11
Answered 2 times

Search




Leave an answer