How to use http delete () in Angular 6

Viewed 67840

myService.ts

  import { Injectable } from '@angular/core';
  import { Http, Response,Headers,RequestOptions } from '@angular/http';
  import { Observable } from 'rxjs';
  import 'rxjs/Rx';
  import{Router} from'@angular/router';
  import 'rxjs/add/operator/map';
  @Injectable()
  export class ManageJobDeleteService{
    constructor(private http: Http,private router:Router){};
    DeleteRequestToAPI(post_jobs_id:string){
       let body = JSON.stringify({post_jobs_id:post_jobs_id});
       let headers = new Headers({ 'Content-Type': 'application/json'});
       let options = new RequestOptions({ headers: headers });
        console.log(body);
        console.log(options);
      return this.http.delete('http://127.0.0.1:8000/api/employer/post_jobs/',body,options)//HERE I AM GETTING ERROR
      .map(this.extractData)
      .catch(this.handleError);
    }
   private extractData(res: Response){
      let body = res.json();
      console.log(body);
      return body || [];   
    }
    private handleError (error: any) {
      console.error(error);
      return Observable.throw(error.json().error || 'Server error');
    }
  }

ERROR:

Expected 1-2 arguments, but got 3.ts(2554).

Please tell me how to pass both body and options using http delete request in Angular 6.

4 Answers

there is no body argument on delete.

so, you need to remove body argument.

this.http.delete('http://127.0.0.1:8000/api/employer/post_jobs/',options)

Reference

class HttpClient {
     delete(url: string, 
       options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; 
       observe?: HttpObserve; params... = {}): Observable<any>
}

Edit: How can I pass post_jobs_id?

you can use HttpParams:

let httpParams = new HttpParams().set('aaa', '111');
httpParams.set('bbb', '222');

let options = { params: httpParams };

this.http.delete('http://127.0.0.1:8000/api/employer/post_jobs/',options);

What about defining your post_jobs_id in your url? And after that get the id in your backend.

For example, you can define :

DeleteRequestToAPI(post_jobs_id:string) {
    const url = `http://127.0.0.1:8000/api/employer/post_jobs/${post_jobs_id}`;
    return this.http.delete(url, {
        headers: new HttpHeaders({ 'Content-Type': 'application/json' })
    })
    .map(this.extractData)
    .catch(this.handleError);
}

I found the best approach for me in using searchParams.

    let url = new URL( this.baseUrl + '/*******');
        url.searchParams.append('llC', llC.toString());
        url.searchParams.append('ulC', ulC.toString());
return this.http.delete(url.toString());

and on the server side you can get

   let data = req.query;
   data['ulC'] ;
   data['llC'] ;

This method works for delete as well as get options!

if your back end is Node and express

router.delete('/post_jobs/:id',(req,res)=>{ let post_jobs_id = req.params.id })

Related