how can I call a delete method properly?

1.4k views Asked by At

It's actually the first time that I'm trying to call a delete method angular. my code in my dataService is:

deleteMeaningItem(data): Observable<Result> {
    return this.http.delete<Result>(url, data);
  }

and in component:

 this.dataService.deleteMeaningItem({id: id}).subscribe(res => {
 if (res.status) {
    //do something          
  }
  });

but I'm getting 415 Unsupported Media Type error! I've also tried to send Content-Type in my request header like:

deleteMeaningItem(data): Observable<Result> {
     return this.http.delete<Result>(global.dataUrl + '/MeaningItems/Delete', { params: data,
     headers: {'Content-Type': 'application/json'}});
}

but then then I'm getting 400 Bad Request error! I need your help.

3

There are 3 answers

1
Qiimiia On BEST ANSWER

all I had to do was to provide body in the request option. so I did this:

deleteMeaningItem(meaningId): Observable<Result> {
    const options = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json',
      }),
      body: meaningId,
    };
    return this.http.delete<Result>(global.dataUrl + '/MeaningItems/Delete', options);
  }
0
BorjaFTW On

Maybe it's easier using RXJS.

First define the delete function @ Service

delete(id: string): Observable<Result> {
 return this.httpClient.delete<Result>(`${global.dataUrl}/MeaningItems/${id}`);
}

Then try to call it like this:

this.service.delete(id).pipe(
  tap(r => console.log('success', r)),
  catchError(e => {
    console.error('error', e);
    return throwError(e);
  })
).subscribe();
1
Dariusz Basiak On

I guess the problem is might be in the data object. I will first check the docs of the API because it looks like you are missing also Autorization header that is usually needed for methods like delete