Get status code http.get response angular2
Asked Answered
W

7

51

I need to get the status code of the following http call and return it as a string

//This method must return the status of the http response
confirmEmail(mailToken):Observable<String>{

     return this.http.get(this.baseUrl+"users/activate?mailToken="+mailToken)
                     .map(this.extractData)
                     .catch(this.handleError);

}

thx!

Werby answered 28/4, 2017 at 14:49 Comment(0)
L
100

Adding answer for versions of Angular >= 4.3 (including 15) with new HttpClient that replaces http

In Angular versions 4.3 and later, the HttpClient module has been introduced, which is an improved version of the old Http module. It allows easier access to HTTP responses, including status code and headers.

Here's an example of how to use it:

In your module, import HttpClientModule:

import { HttpClientModule } from '@angular/common/http'; 
// Notice it is imported from @angular/common/http instead of @angular/http

In your component (if you just care of how to access the status check the console.logs):

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  private baseUrl = 'http://example.com/api/';

  constructor(private http: HttpClient) {
    this.activateUser('mailToken123');
  }

  activateUser(mailToken: string) {
    this.http.get(
      `${this.baseUrl}users/activate?mailToken=${mailToken}`,
      { observe: 'response' }
    )
    .subscribe(response => {
      // Access the status code
      console.log(response.status);
      
      // Access a specific header
      console.log(response.headers.get('X-Custom-Header'));
    });
  }
}

As noted in the comment by @Rbk, the observe: 'response' option passed in the request configuration object is key to getting the full response object, which includes the status code and headers.

Please be aware that not all headers are accessible due to the browser's same-origin policy and the server's Access-Control-Allow-Headers setting. You might not be able to retrieve certain headers unless both conditions are satisfied.

For more information, you can refer to the official Angular HttpClient documentation.

Leptorrhine answered 25/10, 2017 at 16:40 Comment(2)
It must be made clear that to get the full http response object, the option {observe:'response'} is the deciding factor here and then you can return the full response accordingly.Without {observe:'response'},you won't get the full response,only the body data.Mindoro
just add {observe: 'response'} to headerAddictive
M
14

Just modify your code as following to store your responseStatus in a field :

responseStatus: number;

//This method must return the status of the http response
confirmEmail(mailToken):Observable<String> {
//Edited for working with HttpClient on Angular >= 4.3
  return this.http.get(this.baseUrl+"users/activate?mailToken="+mailToken, {observe: 'response'})
                 .map((response: Response) => {
                   this.responseStatus = response.status;
                   return this.extractData(response);
                 }
                 .catch(this.handleError);

}

And then display it in your component HTML template :

<p class='responseStatus'>{{responseStatus}}</p>
Morry answered 28/4, 2017 at 14:53 Comment(6)
Sorry for the inappropriate question, how should I add it to my code?Werby
,write a method called in the service protected extractData(response: Response) { return response.statusText; }Dwinnell
I already have a method with this name: private extractData(res: Response) {let body; try { body = res.json(); }catch (err){ alert(err.message); } return body || { }; }Werby
so in your return call you are returning body which is the response object itself not just the statusText , caller can extract the statusText from it....I suppose you want to return the whole response not just the status textDwinnell
This way I can not interpret the response from the componentWerby
It's not clear, if you want to call your extractMethod and then display the statusCode in your component, you could store this in a field. I edited my answer again.Morry
B
9

Here is the code:

http.get(
   '${this.baseUrl}users/activate?mailToken=${mailToken}',
    {observe: 'response'}
).subscribe(response => {

}, error => {
      // You can access status:
      console.log(error.status);
});

The above code calls the subscribe() method of the instance and then in the error notification, it gets the status.

Billet answered 2/1, 2022 at 11:19 Comment(0)
O
2

Its simple !!

Inside your extractData function

extractData (res){
//res.status  will be your status code
// res.statusText  will be your status Text
}
Optimize answered 28/4, 2017 at 15:23 Comment(0)
D
1
import { HttpClient } from "@angular/common/http";

    constructor(private httpClient: HttpClient) {}
        
    this.httpClient.get<any>(this.API_URL, {observe: 'response'})
        .subscribe({
            next: (res) => {
                console.error(res.status)  // api status in header
                console.error(res.body) // response from api
            }
        });

{observe: 'response'} in get method gives full response object

Decentralization answered 2/8, 2023 at 12:5 Comment(0)
F
0
    confirmEmail(mailToken):Observable<String> {
   return this.http.get(this.baseUrl+"users/activate?mailToken="+mailToken)
     .pipe(map(data => {
       return data.httpStatus
         }));
     .catch(this.handleError);
}

Hope, this will solve your problem.

Fives answered 14/6, 2019 at 19:24 Comment(0)
R
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.errorMessage);
});
    
Robbins answered 26/10, 2022 at 22:13 Comment(2)
HTTP will return the status code when subscribe is successful but if the subscribe is a fail, you did not get the HTTP status codeRenferd
Error message was misspelled.Robbins

© 2022 - 2024 — McMap. All rights reserved.