user2304483
user2304483

Reputation: 1644

How to send array to a get request in Angular 8 app?

I'm trying to send list of ids to the server in a get request, I'm doing the following:

public loadTripsByIds(tripsIds:number[]): Observable<any> {              
    let params = new HttpParams();
    params = params.append('tripsIds', tripsIds.join(', '));    
    return this.http.get<TripObj[]>(`${this.baseUrl}/Trips/ByIds/Get`, {params: params});                        
  }

In the server api code ( rest) I have defined list:

@GET
@Path("Trips/ById/Get") 
@Produces("application/json")
public List<Trips> loadTripsById(@QueryParam("tripsIds") final List<String> tripsIds) {

What I actually getting in the server is a list with 1 item (String type) with comma separated. for example "10001, 10002". I can parse the string in the server side easily but looking for the right way to send list to server where each element will be id.

Thanks.

Upvotes: 0

Views: 6841

Answers (2)

user2304483
user2304483

Reputation: 1644

In order to solve the problem I;m sending now array of param as follow:

let params = new HttpParams();
    for (let id of tripsIds) {
      params = params.append('tripIds', id); 
    }  

Upvotes: 5

Reactgular
Reactgular

Reputation: 54771

I am not a Java/Sprint developer, but some back-end frameworks handle duplicate query parameters as a collection. So you need a URL that looks like this.

http://example.com/?id=1&id=2

So try this, but I do not know if this helps.

const params = tripIds.reduce((acc, next) => acc.append('tripsIds', next), new HttpParams());

Upvotes: 1

Related Questions