How can get the status code of the HttpClient module in angular

Viewed 2198

How to get the status code of all the request using HttpClient

apiCall() {
    let header1 = new HttpHeaders();
    header1 = header1.append('Content-Type', 'application/json');
    header1 = header1.append('Authorization', `Bearer ${this.token}`);

    this.http.post("URL",
      {
        "dataSentHere": "data"
      }, {
      headers: header1
    }).subscribe(data => {

      console.log(data);

    },
      (err: HttpErrorResponse) => {
        if (err.status === 403) {
         console.log("403 status code caught");
        }
      }

      
    )
  }

How to get the status code of the http request which returns 202 , 200 etc.

1 Answers

Use HttpErrorResponse and HttpResponse from '@angular/common/http'

apiCall() {
  let headers = new HttpHeaders();
  headers = headers.set('Content-Type', 'application/json');
  headers = headers.set('Authorization', `Bearer ${this.token}`);

  this.http.post<HttpResponse<any>>('URL', { data }, { headers }).subscribe(response => {
      console.log(response.status) // log status code
  }, (e: HttpErrorResponse) => console.log(e.status))

}
Related