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
  • 9,685
  • 7
  • 35
  • 75
Lenin J
  • 15
  • 4

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
  • 35,416
  • 5
  • 56
  • 100
  • Thanks @sidd. My API accepts an array and return pets respective to the owners. Anyways cant we send an array through GET? Stringifying is the option? Or may be i should change my API to POST! – Lenin J Jul 16 '19 at 06:58
  • I think it's better that you change it to post. I'd call what you're doing currently as an anti-pattern. And it literally won't make much sense the way you're doing it. If you want to make it a get request, pass owners as queryParams. check out the second code snippet in my answer for the same. – SiddAjmera Jul 16 '19 at 07:00
  • @LeninJ, does that answer your question? – SiddAjmera Jul 17 '19 at 01:13
  • I have changed my API. Thanks for the response guys. – Lenin J Jul 17 '19 at 07:12
  • Awesome. If this answer was the solution to your issue, please consider marking it as a solution( ✔️) to close the loop. Thanks. – SiddAjmera Jul 17 '19 at 07:28
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