Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing array into URLSearchParams while consuming http call for get request

Going through the Angular documentation for URLSearchParams, I dint find any documentation on passing array as an parameter.

Can anybody help with that?

like image 268
Madhu Ranjan Avatar asked Aug 05 '16 20:08

Madhu Ranjan


3 Answers

In fact, you can't pass an array directly but you can use several times the append method:

let params = new URLSearchParams(); params.append('arrayparams', 'val1'); params.append('arrayparams', 'val2'); params.append('arrayparams', 'val3'); console.log(params.toString());
like image 105
Thierry Templier Avatar answered Sep 25 '22 18:09

Thierry Templier


URLSearchParams can be passed a sequence of pairs, so to have an array of values:

var ids = [1,2,3,4]
var search = new URLSearchParams(ids.map(s=>['id',s]))
var searchString = search.toString()
// "id=1&id=2&id=3&id=4"
// To get the ids from the URL search string
var search_ids = [...search.getAll('id')]
like image 30
nmattise Avatar answered Sep 24 '22 18:09

nmattise


If you want to use @washington-braga's approach but don't want to install lodash:

function buildParams(data) {
    const params = new URLSearchParams()

    Object.entries(data).forEach(([key, value]) => {
        if (Array.isArray(value)) {
            value.forEach(value => params.append(key, value.toString()))
        } else {
            params.append(key, value.toString())
        }
    });

    return params.toString()
}
like image 36
richbray89 Avatar answered Sep 26 '22 18:09

richbray89