11

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

  }
}

3 Answers 3

10

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)
})
          },
Sign up to request clarification or add additional context in comments.

Comments

9

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 -

2 Comments

this.http.get('restcountries.eu/rest/v2/all',{ observe: 'response'}).subscribe(res => { this.countries=res; },err=>{ });
as you said i wrote code above but atlease response also not coming now
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.