Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass an array within a query string in HttpClient?

This is my array of actors:

['Elvis', 'Jane', 'Frances'] 

How to pass this array within a query string in HttpClient?

I tried to use:

1)

let params = new HttpParams(); params = Params.append('actors[]', ['Elvis', 'Jane', 'Frances']); this.http.get(url, { params: Params }); 
let params = new HttpParams().set('actors[]', ['Elvis', 'Jane', 'Frances']); this.http.get(url, { params: Params }); 
let Params = new HttpParams(); Params = Params.append('actors[]', 'Jane'); Params = Params.append('actors[]', 'Elvis'); Params = Params.append('actors[]', 'Frances'); this.http.get(url, { params: Params });  

1st and 2nd snippets don't work because of TypeScript error:

[ts] Argument of type 'string[]' is not assignable to parameter of type 'string'.

3rd snippet sends only one item 'actors[]': 'Frances'

like image 229
Dmitry Grinko Avatar asked Nov 10 '17 07:11

Dmitry Grinko


People also ask

Can we send array in query string in Javascript?

The answer is you can't, not with Javascript. All solutions you end up would not be actually something you would pass. What you can do is pass an array like parameter and throw back with you server side languague.

How do I use HttpParams?

To use HttpParams , you need to import it first as shown below. import { HttpClient,HttpParams } from '@angular/common/http'; Then create an instance of the HttpParams class.


1 Answers

I think the best way is to add them to parameters as a string and have your back-end convert it back to an array or list.

let actorList = ['Elvis', 'Jane', 'Frances'] let params = new HttpParams(); params = params.append('actors', actorList.join(', ')); this.http.get(url, { params: params }); 
like image 112
Venomy Avatar answered Oct 10 '22 18:10

Venomy