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'
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.
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.
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 });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With