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 = ' 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

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

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

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

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy