简体   繁体   中英

Angular HttpClient request method how to set body

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM