I am making an Angular frontend and got really unexpected behaviour after an HTTP DELETE
call.
When in component code I call directly HttpClient.delete
, it logs 'test'.
If I call the delete in a method of same file, delete2
, it logs 'test2'.
When I put same delete method in a service.ts
file injected in the constructor like usual, DELETE
is performed on the browser but 'test4' IS NOT LOGGED in the console ('delete3' from service is logged, 'test error3' is not logged either).
constructor(
private service: Service,
private http: HttpClient
) { }
// delete action code triggered by user
this.http.delete("http://localhost:4200/").subscribe({
next: () => { console.log("test"); },
error: () => { console.log("error test"); }
});
this.delete2("http://localhost:4200/").subscribe({
next: () => { console.log("test2"); },
error: () => { console.log("error test2"); }
});
this.service.delete3("http://localhost:4200/").subscribe({
next: () => { console.log("test4"); },
error: () => { console.log("error test3"); }
});
delete2(path: string): any{
return this.http.delete<Company>(path);
}
Service file:
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Company } from './company.model';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class Service {
constructor(
private http: HttpClient
) { }
delete3(path: string): Observable<Company> {
console.log("delete3");
return this.http.delete<Company>(path);
}
}
I was trying to refresh my list after the user delete one record, so I wanted to call my get function after delete in the subscribe callback of the Observable returned by http.delete
, but the callback code is never called.
It works with HttpClient.get
though, I do not know why.
I have the save problem with PUT
and POST
, DELETE
is just an easier example.
Check if delete api is returning any response body. If not, that can be the root cause. Angular was trying to parse the DELETE response as Company (JSON) but your server likely returned 200 OK with no JSON.