[Fixed] How to get status code from Angular service

Issue

I have an API that, when I initiate a http delete it will return NoContent.

In my Angular service and component, I need to check that status code to make sure it returned no content (204) that the delete was successful as opposed to another error code (ie 404 or 400).

How would I get access to that response? My code is generating a Property 'httpStatus' does not exist on type 'Object'. Error.

My service:

deleteData(id: number)  {
      return this.http.delete(this.baseUri + id)
      .pipe(
        map(data => {
          return data.httpStatus
        }),
        catchError(err => of(null))
      );
    }

In the component which calls the service:

deleteDataObj(id: number) {
    this.dataService
    .deleteData(id)
    .subscribe(
      (apiResp: any) => {
        console.log(apiResp.headers.get('Status Code'));
      },
      (err: any) => {
        console.log(err)
      }
    )
  }

Solution

You need to observe the api service response. Please try with the below code,

deleteData(id: number)  {
      return this.http.delete(this.baseUri + id, {observe : 'response'});
}

Then in your component you will got the status code

deleteDataObj(id: number) {
    this.dataService
    .deleteData(id)
    .subscribe(
      (apiResp: any) => {
        console.log("status code--->" + apiResp.status);
      },
      (err: any) => {
        console.log("status code--->" + err.status);
      }
    )
}

For more reference please refer this link how to read full response.

Leave a Reply

(*) Required, Your email will not be published