0
let owners = ['Chris', 'John'];

this.http.get('/pets', {'owners': owners}).subscribe(...);

The request goes like .../pets/owners=Chris&owners=John

But I want to request like .../pets/owners=['Chris', 'John'].

Are there any ways to achieve this?

Prashant Pimpale
  • 10,349
  • 9
  • 44
  • 84
Lenin J
  • 15
  • 5

2 Answers2

3

I'm just curious as to why is your API is expecting you to send the request something like this?

This data that you're sending should be either sent as a request payload to a POST request. Something like this:

let owners = ['Chris', 'John'];
this.http.post(`/pets/owners`, { owners }).subscribe(...);

Or you should send it as a GET request but then as query params in that case:

let owners = ['Chris', 'John'];
this.http.get(`/pets?owners=${owners.toString()}`).subscribe(...);

If you still are sending the data like this, how exactly is your server intercepting this request? Why I'm asking that is because you are not setting the owners array as a value to anything.

If you still want to sent it like this, here's how you'd do that:

let owners = ['Chris', 'John'];
this.http.get(`/pets/owners=${JSON.stringify(owners)}`).subscribe(...);

But then again, I'm not really sure how your backend is making sense of this request.

SiddAjmera
  • 38,129
  • 5
  • 72
  • 110
0

I would suggest rather using a post request and passing the list of owners in the request body.

e.g.:

public serviceMethod(owners): Observable<expectedType> {

  let headers = new HttpHeaders();
  headers = headers.set('Content-Type', 'application/json');

  let params = new HttpParams();
  return this.http.post('/pets', owners, {headers: headers, params: params});
}

You can then subscribe to the service method where you need to use it:

service.serviceMethod(['Chris', 'John']).subscribe(...);
Langz020
  • 46
  • 4