Angular 7 Http delete api handle body?

18,817

Solution 1

this will work for angular 6+, where http is your HttpClient

const options = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json'
      }),
      body: {
        name: 'ravi',
        id: 'ravi123'
      }
    }

    this.http.delete('http://localhost:8080/user', options).subscribe(s => {
      console.log(s);
    })

Solution 2

Using http.delete didn't work for me on angular6, nor angular9. I had to use this.http.request('delete', url, options) instead.
Also, Typescript seems to have some issue about typing the response, so I had to force the result type manually with the map operator:

const httpOptions: any = {
  headers: {
    'Content-Type': 'application/json'
  }
};
const uri = '/path/to/delete/api';

httpOptions.body = {
  prop1: value1,
  prop2: value2
  // ...
};

return this.http.request<string>('delete', uri, httpOptions).pipe(
  map((result: any) => result as string), // fix typescript typing
  tap((result: string) => {
    console.log('response from server:', result);
  }
);
Share:
18,817
Admin
Author by

Admin

Updated on June 05, 2022

Comments

  • Admin
    Admin almost 2 years

    I'm trying to talk to a somewhat REST API from an Angular 7 front end.

    To remove some item from a collection, I need to send some other data in addition to the remove unique id, namely an authentication token, some collection info and some ancillary data.

    However, the Http module of Angular 7 doesn't quite approve of a DELETE request with a body, and trying to make this request.

    Here is my api:

    DELETE /user/verifications
    
    body {
      "doc_type": "govt_id",
      "doc_id": "5beedd169db947867b710afd"
    }
    
  • Random
    Random about 4 years
    Didn't work for me on angular6. I had to use this.http.request('delete', url, options) instead
  • ravi
    ravi about 4 years
    was it giving any errors when you used "this.http.delete" method
  • Random
    Random about 4 years
    saying body is not a valid key within the 2nd parameter (options)
  • ravi
    ravi about 4 years
    can you please add some code, like how you have implemented and what body is
  • Random
    Random about 4 years
    Nothing particular, my service is already doing multiple other http calls, and I'm used to code http calls so nothing weird here. The options object had 2 attributes: headers which is { 'Content-Type': 'application/json' } and body which is { ts: xxx }