How to pass an array within a query string in Http

2020-05-31 05:40发布

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 });

2)

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

3)

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 }); 

1 and 2 doesn't work so as typescript gives:

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

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

8条回答
欢心
2楼-- · 2020-05-31 06:26
let actorsArray = ['Elvis', 'Jane', 'Frances'];
this.http.get(url, { params: { actors: actorsArray } });
查看更多
Emotional °昔
3楼-- · 2020-05-31 06:27

According the interface you can do that like

const params = new HttpParams({ 
   fromObject: { 'actors[]': ['Elvis', 'Jane', 'Frances'] } 
});
this.http.get(url, { params });
查看更多
登录 后发表回答