Angular make a get passing array?

Forums AngularAngular make a get passing array?
Staff asked 1 month ago

I’m trying to create an api call with an array of ids as the parameter.

in my web page ts file:

this.myService.getPassingID(['1', '2'])
 .subscribe((val) => console.log("val", val))

in my service:

getPassingID(id): Observable<any>{
let params = new HttpParams()
      .set("id", id)
let url = apiURL 
return this.http.get(url, {params});
}

This is how I attempted it, however I got a 500 error. What is the best way to pass an array in an API call?

Answers (1)

Add Answer
Staff answered 1 month ago

#1 Stringify the array and feed it into params before sending it to the HTTP call.

let params = new HttpParams().set("id", JSON.stringify(id));

At your receiving API backend, you’ll need to parse the relevant param.

JSON.parse(params.id)

and put it to good use.

#2 In the id param, append all of the array’s items as comma(,) separated values.

let params = new HttpParams();
params = params.append('id', id.join(','));

At the backend, this can be accessed and divided on comma(,).

let idArray = params.id.split(',');

and put it to good use.

Thank you

John Price replied 1 month ago

Subscribe

Select Categories