Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send array via GET request with AngularJS' $http service

I need to send a GET request using the $http service. One of the parameters will be an array of ids. The url looks like this one mysite.com/items?id[]=1&id[]=2&id[]=3&id[]=4

I tried this approach

$http(   method: 'GET',   url: '/items',   params: {     id: ids // ids is [1, 2, 3, 4]   } ) 

but the url I obain is mysite.com/items?id=%5B%221%22%2C%222%22%2C%223%22%2C%224%22%5D

That's Because Angular is converting my value in a JSON string. Is there a way to get the behavior I want?

[Update]

I solved the issue thanks to Jonathan's suggestion using jQuery's $.param().

$http(   method: 'GET'   url: '/items?' + $.param({id: ids}) ) 
like image 875
Giorgio Polvara - Gpx Avatar asked Nov 13 '13 15:11

Giorgio Polvara - Gpx


People also ask

What is $HTTP in AngularJS?

$http is an AngularJS service for reading data from remote servers.

How do we pass data and get data using http in angular?

Use the HttpClient.get() method to fetch data from a server. The asynchronous method sends an HTTP request, and returns an Observable that emits the requested data when the response is received. The return type varies based on the observe and responseType values that you pass to the call.

How do you modify the $HTTP request default Behaviour?

To add or overwrite these defaults, simply add or remove a property from these configuration objects. To add headers for an HTTP method other than POST or PUT, simply add a new object with the lowercased HTTP method name as the key, e.g. $httpProvider. defaults.

Which of the following is the correct syntax for making a get call and handling the error in angular?

get(url) . then(function (response) { console. log('get',response) }) . catch(function (data) { // Handle error here });


2 Answers

You can also just do

$http(   method: 'GET',   url: '/items',   params: {     "id[]": ids // ids is [1, 2, 3, 4]   } ) 

as mentioned here. Seems simpler.

like image 126
Ignacio Valdivieso Avatar answered Oct 02 '22 20:10

Ignacio Valdivieso


$http(   method: 'GET',   url: '/items',   params: {     id: JSON.stringify(ids) // ids is [1, 2, 3, 4]   } ) 
like image 31
Saad Ahmed Avatar answered Oct 02 '22 19:10

Saad Ahmed