Home > other >  Angular make a get passing array
Angular make a get passing array

Time:04-09

I'm trying to make an api call passing an array of id

in my page.ts:

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

I have tried in this way but I receive 500 error. How can I pass array in api call?

CodePudding user response:

You can pass it in two ways.

#1 Stringify the array while passing it into params and then send it to the HTTP call

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

This needs you to parse the respective param at your receiving API backend.

JSON.parse(params.id)

and use it further.

#2 Append all the elements of the array as comma(,) separated values into the id param.

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

This can be accessed and split on comma(,) at the backend.

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

and use it further.




Upvote if helps :)

  • Related