Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling error in http calls in ionic 2

In my Ionic2 app, I have a service which handles all http requests. I have an alert controller when any error occurs in http call. On button click in this alert I want to run that call again. I am able to do it right now. The problem is response is not resolved to page from which function was called.

Code in service:

loadCity(){
return new Promise(resolve => {
this.http.get(url).map(res=>res.json())
.subscribe(data => {resolve(data)},
err => { this.showAlert(err); }
});
}

showAlert(err: any){
// code for alert controller, I am only writing handler of alert 
//controller refresh button
handler => {this.loadCity();}
}

Code in CityPage

showCity(){
this.cityService.loadCity()
.then(data => {//process data});
}

Handler is calling function again but this time promise is not resolved to CityPage showCity() function.

like image 610
Vivek Sinha Avatar asked Mar 25 '26 19:03

Vivek Sinha


1 Answers

When an error occurs in the http request, the error callback function is being called, but you are neither resolving nor rejecting the promise.

You can do something like

loadCity(){
    return new Promise( (resolve, reject) => {
        this.http.get(url).map(res=>res.json())
        .subscribe(
            data => {resolve(data)},
            err => { 
                this.showAlert(err);
                reject(err);
            }
        });
    }
}

and in the caller

showCity(){
    this.cityService.loadCity()
    .then( data => {
        //process data
    })
    .catch( error => {
        //some error here
    })
}

You can see better examples in the docs.

like image 67
Christian Benseler Avatar answered Mar 29 '26 04:03

Christian Benseler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!