0

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?

Learner
  • 549
  • 3
  • 15
  • 1
    why don't just _localhost:8000/api/somePerson/someMethod?values=1,2,3,4_ – Nick Dec 14 '21 at 15:40
  • 1
    Maybe it's because you are calling `getParamsView` to get params, when the functions is named `getParams`? At least, it is according to what you have posted. – R. Richards Dec 14 '21 at 15:41
  • @R.Richards sorry, it is typo. I’ve updated answer – Learner Dec 14 '21 at 15:58
  • 1
    @Nick I do not know. Is it best practise ti send parameters like you asked? – Learner Dec 14 '21 at 15:59
  • @Learner if you just want multiple values for a single parameter i would suggest to go for that and in your route handler split them with .split(',') and that's it, you have now an array of values – Nick Dec 14 '21 at 17:03

2 Answers2

2

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;
}
Bálint Réthy
  • 394
  • 1
  • 4
  • 21
1

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 */
});
Nick
  • 593
  • 12