Home > Net >  Add multiple parameters with same name in Angular 11
Add multiple parameters with same name in Angular 11

Time:12-15

What I want to do is adding multiple parameters with same name to request URL with Angular 11:

http://example.com/somepath?data=1&data=2&data=3

I've seen this post, but accepted answer is not eligible to me because it is Angular 1.

What I've tried is:

private getParams(value: string): HttpParams {
    const values = value.split("/");    

    const httpParams = new HttpParams();    

    values.forEach((item) => httpParams.set('value', item));    
    return httpParams;
}

and then I try to send it:

public getConfig(view: string): Observable<IFooBar[]> {
    const params = this.getParams(view);
    return this.http.get<IFooBar[]>(`$somePerson/someMethod`, { params });  
}

But what url becomes is without params:

http://localhost:8000/api/somePerson/someMethod

How to send parameters with the same name?

CodePudding user response:

Reason is set and append returns a new instance so make sure you keep it updated. Based on doc.

let params = new HttpParams().append('value', '1');
params = params.append('value', '2');
params = params.append('value', '3');
params = params.append('value', '4');

console.log(params.getAll('value'));

So you should write something like this:

private getParams(value: string): HttpParams {
  const values:string[] = value.split("/");    

  let httpParams:HttpParams = new HttpParams();    

  values.forEach((item) => {
    httpParams = httpParams.append('value', item)
  });    

  return httpParams;
}

CodePudding user response:

In your case i would probably pass more values on the same parameter like this:

public getConfig(view: string): Observable<IFooBar[]> {
    const params = [1, 2, 3, 4, 5, 6];
    return this.http.get<IFooBar[]>('somePerson/someMethod', { params: { values: params.join(',') } });  
}

And in your server endpoint(posting an example with express):

app.get('somePerson/someMethod', (req, res) => {
    const values = req.query.values?.split(',');
    /* Now you have your values as an array of values */
});
  • Related