Angular HttpClient request method how to set body
Asked Answered
C

2

8

I need to send a get request with body. Im using angular HttpClient. I understand that get method does not allow to send body, so i'm triyng the request method instead but i cant understand how to use it.

I was able to get data from the exemple bellow without the body part, but i really need to send the body as JSON format.

    request(req?: any): any{

    const options = createRequestOption(req);
    return this.http
        .request<ISubscriber[]>("GET", this.resourceUrl,
        {
            body: '[{"key": "phoneLineType", "operation": ">", "value": "200"}]',
            headers: new HttpHeaders({'Content-Type' : 'application/json'}),
            params: options,
            observe: 'response'
        });
}
Concave answered 15/1, 2019 at 10:24 Comment(3)
There is no body in GET requests, as you said. request won't change that : get is just a shorthand for request('GET').Irena
I think that what you are looking for is a POST request, look into angular.io/guide/http#making-a-post-requestRambouillet
Thank you for your reply trichetriche. Can you tell me if the URL would be inside REST standard? /api/subscribers/?id=key1,op1,value1&name=key2,op2,value2 i think this way i would be able to solve my problem as wellConcave
S
5

Using http.get() is just a shorthand for http.request('GET'). If you really need to send a JSON body, then you'll have to use another type of request - such as post. Something like this might be what you need:

return this.http
  .post<ISubscriber[]>(
    this.resourceUrl,
    '[{"key": "phoneLineType", "operation": ">", "value": "200"}]',
    {
      params: options
    {
  )

You may need to change your API endpoint to expect a different HTTP verb.

Statistician answered 15/1, 2019 at 10:53 Comment(0)
C
0

I followed your advice and here is my solution for others in the future...

queryPost(body: string, req?: any) : any {

    const options = createRequestOption(req);
    return  this.http.post<ISubscriber[]>(this.searchUrl, body,
            {
                headers : new HttpHeaders({"Content-Type": "application/json"}),
                params: options,
                observe: 'response'
            });
}

As also mentione i had to creatre a new Post end point in my back end app.

Thank you all

Concave answered 15/1, 2019 at 11:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.