4

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.

Santhosh
  • 810
  • 2
  • 10
  • 28
  • 3
    Does this answer your question? [Get status code http.get response angular2](https://stackoverflow.com/questions/43683052/get-status-code-http-get-response-angular2) – Tobias S. Nov 09 '21 at 12:57
  • still how to print the status code which is 200, 201, 205 etc – Santhosh Nov 10 '21 at 04:48
  • literally the first answer of the mentioned post shows how to print the status code – Tobias S. Nov 10 '21 at 09:17

3 Answers3

4

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))

}
Khumo Mogorosi
  • 301
  • 2
  • 7
2

You need to add observe: 'response' to the options parameter. By doing this you would have the whole response available in your subscription.

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

    this.http.post<HttpResponse<any>>(
      'URL',
      {
        dataSentHere: 'data',
      },
      {
        headers: header1,
        observe: 'response',
      },
    ).subscribe(
      (data: HttpResponse<any>) => {
        if (data.status === 200 || data.status === 202) {
          console.log(`Got a successfull status code: ${data.status}`);
        }
        console.log(`This contains body: ${data.body}`);
      },
      (err: HttpErrorResponse) => {
        if (err.status === 403) {
          console.error('403 status code caught');
        }
      },
    );
  }

Reference: https://angular.io/guide/http#reading-the-full-response

schwartz
  • 189
  • 8
0

If your using HttpClient, here is an example:

this.http.post(myRequest, body, { headers : myHeaders, observe: 'response' }).subscribe(
  data => {
    console.warn(JSON.stringify(data, null, 2));
  },
  error => {
    console.error(error.errorMessege);
});
Fritz
  • 343
  • 1
  • 10