Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a body to Angular HttpClient delete function

People also ask

Can you add a body to delete request?

Yes it is allowed to include a body on DELETE requests, but it's semantically meaningless. What this really means is that issuing a DELETE request with a request body is semantically equivalent to not including a request body.

What is the return type of HttpClient post delete request?

HttpClient is one of the best APIs to make HTTP requests. It returns an Observable, but if you want to return a Promise that can also be done using HttpClient. It is best practice to return an Observable and subscribe it in other functions.

How do I remove HttpClient?

An HTTP Delete request can be sent to delete a resource from the API server using the DeleteAsync () method provided by the HttpClient class.

What is delete in Angular?

The delete method is used to delete the resource from a server. Delete request makes a change in the server state. Sending the message on a delete request might cause some services to reject the request but you still send the data to the server using URL Parameter.


You may use a universal request method on the HttpClient class instead. This method has the body in options. https://angular.io/api/common/http/HttpClient#members

e.g this.http.request('delete', 'url', { body: ... })


const httpOptions = {
    headers: new HttpHeaders({ 'Content-Type': 'application/json' }), body: your body data
};


return new Promise(resolve => {
    this.httpClient.delete(URL, httpOptions)       
                   .subscribe(res => {     
                       resolve(res);
                   }, err => {               
                       resolve(err);
                   });
    });

by using httpOptions, you can set header and body in it. please refer this https://angular.io/tutorial/toh-pt6#delete-a-hero


I also get this problem and my solution is creating a new HttpRequest of delete method, then clone this request, reset its body with your data.

let req = new HttpRequest('DELETE', 'url');
let newReq = req.clone({body: [10]});
this.http.request(newReq).subscribe((res) => {
    console.log(res);
}, (err) => {
    console.log(err);
});

The clone() is required, because the body still can not be directly set in the new HttpRequest().