Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can we get HttpClient Status Code in Angular 4

Tags:

angular

Hi new for Angular and i am facing problem for getting HTTP status code that is In HTTP Module I can easily get the response code using response.status, but when I used HttpClient Module I can not get the response.status, it shows can not find status.

So, how can I get the response.status using HttpClient module in Angular 4&5. Please help.

RestProvider:-

@Injectable()
export class RestProvider {

  private apiUrl = 'https://restcountries.eu/rest/v2/al';

  constructor(public http: HttpClient) {
    console.log('Hello RestProvider Provider');
  }

  getCountries(): Observable<{}> {
    return this.http.get(this.apiUrl).pipe(
      map(this.extractData),
      catchError(this.handleError)
    );
  }

  private extractData(res: Response) {
    let body = res;
    return body || { };
  }

  private handleError (error: Response | any) {
    let errMsg: string;
    if (error instanceof Response) {
      const err = error || '';
      errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
    } else {
      errMsg = error.message ? error.message : error.toString();
    }
    console.error(errMsg);
    return Observable.throw(errMsg);
  }

}

HomePage:

export class HomePage {

  responseStatus: number;

  countries: any;
  errorMessage: string;

  constructor(public navCtrl: NavController, public navParams: NavParams, public rest: RestProvider) {
  }

  ionViewDidLoad() {
    this.getCountries();
  }

  getCountries() {
    this.rest.getCountries().subscribe(res =>{
      this.countries=res;
      console("status code--->"+res.status)
    },
    err=>{
      console("status code--->"+err.status)
    })

  }
}
like image 638
AbhiRam Avatar asked Jun 19 '18 04:06

AbhiRam


People also ask

How do I get HttpClient response code?

HttpClient client = new DefaultHttpClient(); HttpGet response = new HttpGet("http://www.example.com"); ResponseHandler<String> handler = new BasicResponseHandler(); String body = client. execute(response, handler);

How can I get status code from HTTP status?

To get the status code of an HTTP request made with the fetch method, access the status property on the response object. The response. status property contains the HTTP status code of the response, e.g. 200 for a successful response or 500 for a server error.

What is the use of HttpClient get () method?

Use the HttpClient.get() method to fetch data from a server. The asynchronous method sends an HTTP request, and returns an Observable that emits the requested data when the response is received. The return type varies based on the observe and responseType values that you pass to the call.

What is the status code in HTTP?

An HTTP status code is a server response to a browser's request. When you visit a website, your browser sends a request to the site's server, and the server then responds to the browser's request with a three-digit code: the HTTP status code.


3 Answers

To get full response you need to add extra property to response which is observe like this -

getCountries(): Observable<{}> {
    return this.http.get(this.apiUrl, {observe: 'response'}).pipe(
      map(this.extractData),
      catchError(this.handleError)
    );
  }

For more information you can refer -

  • https://angular.io/guide/http#reading-the-full-response
  • HttpClient get status + send headers
like image 89
Pardeep Jain Avatar answered Oct 02 '22 20:10

Pardeep Jain


Add observe : 'response' in header options of http.get method like

getCountries(): Observable<{}> {
    return this.http.get(this.apiUrl,{observe : 'response'}).pipe(
      map(this.extractData),
      catchError(this.handleError)
    );
  }

and subscribe to get() method to get response status whatever you want in your HomePage like you have done

 getCountries() {
this.rest.getCountries().subscribe(
    res => {  this.countries=res;
  console("status code--->"+res.status)
},
err=>{
  console("status code--->"+err.status)
})
          },
like image 42
Rohit Kavthekar Avatar answered Oct 01 '22 20:10

Rohit Kavthekar


You can use Angular's interceptor to catch all the errors in one place and keep your services neat. Create a new interceptor called "error-interceptor" and add the intercept method:

  intercept(request, next) {
    // Handle response
    return next.handle(request).pipe(
      catchError(error => {
        //handle specific errors
        if (error.status === 401) {
          this.handle401();
        }

        //default case: print, log, toast, etc...
        return throwError(error.message || error);
      })
    );
  }
like image 2
NicuVlad Avatar answered Oct 04 '22 20:10

NicuVlad