http - 处理 ionic 2 中的 http 调用错误

标签 http ionic-framework promise ionic2

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

服务中的代码:

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

CityPage 中的代码

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

Handler 再次调用函数,但这次 promise 没有解析到 CityPage showCity() 函数。

最佳答案

当http请求发生错误时,正在调用错误回调函数,但你既没有解决也没有拒绝promise。

你可以做类似的事情

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

在调用者中

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

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

关于http - 处理 ionic 2 中的 http 调用错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44259674/

相关文章:

javascript - 为什么我会收到 SyntaxError : Unexpected identifier in forEach with await?

node.js - `fs-extra` 与 `bluebird ` 集成得到 `Cannot read property ' 然后 ' of undefined` 错误

php - 如何在 PHP 中将 HTTP 请求中的所有信息打印到屏幕

jquery - 当 json 字符串中有 & 登录时,http post 请求中的数据中断

angular - ionic 问题 : [ng]Schema validation failed with the following errors:[ng]Data path". build 者 ['app-shell' ]"should have required property ' 类'

object - Ionic 3 使用 navparams 将对象传递到 3 个页面

javascript - 我如何嵌套 2 个 promise 并让 ionViewCanLeave 等待结果?

windows - 在 IIS 中禁用匿名访问是否会带来安全风险?

http - 在创建 AJAX 请求的上下文中,GET 和 POST 有什么区别?

angular - ionic 4 infinite scroll 只工作一次