处理离子2中http调用中的错误

Viv*_*nha 2 http promise ionic-framework ionic2

在我的Ionic2应用程序中,我有一个处理所有http请求的服务.当http调用中发生任何错误时,我有一个警报控制器.在按钮上单击此警报我想再次运行该调用.我现在能够做到.问题是响应未解析为从哪个函数调用的页面.

服务代码:

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();}
}
Run Code Online (Sandbox Code Playgroud)

CityPage中的代码

showCity(){
this.cityService.loadCity()
.then(data => {//process data});
}
Run Code Online (Sandbox Code Playgroud)

处理程序再次调用函数,但此时承诺未解析为CityPage showCity()函数.

Chr*_*ler 10

当http请求中发生错误时,将调用错误回调函数,但您既不会解析也不会拒绝承诺.

你可以做点什么

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

并在呼叫者

showCity(){
    this.cityService.loadCity()
    .then( data => {
        //process data
    })
    .catch( error => {
        //some error here
    })
}
Run Code Online (Sandbox Code Playgroud)

您可以在文档中看到更好的示例.