This is my array of actors:
[\'Elvis\', \'Jane\', \'Frances\']
How to pass this array within a query strin
I've used this method and it worked for me in Angular 10:
private paramMaker(data) : HttpParams
{
let httpParams = new HttpParams();
Object.keys(data).forEach((key) = > {
if (Array.isArray(data[key]))
{
data[key].forEach((item, index) = > {
httpParams = httpParams.append(key + '[' + index + ']', item);
});
}
else
{
httpParams = httpParams.append(key, data[key]);
}
});
return httpParams;
}
Yo can simply do this by using JSON.stringify()
let params = new HttpParams();
const actors = ['Elvis', 'Jane', 'Frances'];
params.append('actors', JSON.stringify(actors);
this.http.get(url, { params: params });
This worked for me.
let params = new HttpParams();
['Elvis', 'Jane', 'Frances'].forEach((actorName:string) =>{
params = params.append(`actors[]`, actorName);
})
OR
let params = new HttpParams();
let actorsArray:Array<string> = ['Elvis', 'Jane', 'Frances'];
actorsArray.forEach((actorName:string) =>{
params = params.append(`actors[]`, actorName);
})
According the interface you can do that like
const params = new HttpParams({
fromObject: { 'actors[]': ['Elvis', 'Jane', 'Frances'] }
});
this.http.get(url, { params });
Works on Angular 6.0.6:
private getParams(query) {
let params: HttpParams = new HttpParams();
for (const key of Object.keys(query)) {
if (query[key]) {
if (query[key] instanceof Array) {
query[key].forEach((item) => {
params = params.append(`${key.toString()}[]`, item);
});
} else {
params = params.append(key.toString(), query[key]);
}
}
}
return params;
}
Result:
/api/message?page=1&per=2&order_by=name&order_direction=asc&base_object%5B%5D=2&base_object%5B%5D=1
I'm using URLSearchParams
instead of HttpParams.
With URLSearchParams you need to stringify your array to set it to your Params "Key-Value-Store".
import { URLSearchParams } from '@angular/http';
let params: URLSearchParams = new URLSearchParams();
params.set('actors', JSON.stringify(yourArrayHere));
I think this should work on the same way with HttpParams because both using a Key-Value mapping in the set method so give it a try.
I hope this can help you.
UPDATE:
let options = new RequestOptions({search: params});
this._http.get(url, options).map(...)
with RequestOptions
you can also edit Header and other request options.