【问题标题】:How to show alert for slow internet in Ionic2?如何在 Ionic2 中显示慢速互联网警报?
【发布时间】:2017-01-05 14:50:16
【问题描述】:

我想检测 ionic2 应用程序中的慢速互联网并处理它。

我已经完成了谷歌和使用 settimeout 的方法,但是在调用 api 时如何使用它?

我将 api 称为:

   AppSettings.API_ENDPOINT = is a constant having api url.

 this.returned = this.http.post(`${AppSettings.API_ENDPOINT}login`, "email=" + email + "&password=" + password, { headers: headers }).timeout(100).map(res => res.json()).subscribe(data => {

            this.conn_error_msg = '';

            if (data.status == 200) {


            }
            else {

            }

        }, 
        error => {
            this.isDisabled = 0;
            this.conn_error_msg = 'Internet connection error. Please try again.';
            console.log(JSON.stringify(error.json()));
            loader.dismiss();
        }
        );

使用这种方式我的超时工作正常,但我需要显示警报..

在这里我希望在超时时显示警报

已解决:

this.http.get(url)

.timeout(1000) 。地图(...) .subcribe((success) => {...}, (err) => { // 这里处理超时错误。});

希望它对某人有所帮助。

编码愉快。

【问题讨论】:

  • 可以使用 rxjs 超时。

标签: angular ionic2


【解决方案1】:

调用api时可以这样设置超时时间:

import 'rxjs/add/operator/timeout';

return this.http.get(yourUrl).timeout(50000, new Error('Timeout!'));

当然,使用 post/put... 方法时也可以这样做。

【讨论】:

  • 错误函数需要调度程序类型。我收到此错误:“错误”类型的参数不可分配给“调度程序”类型的参数。 “错误”类型中缺少属性“SchedulerAction”
  • @sebaferreras: 我用它作为 :: this.http.post(${AppSettings.API_ENDPOINT}login, "email=" + email + "&password=" + password, { headers: headers }).map( res => res.json()).timeout(50000, new Error('Timeout!')).subscribe(data => {
  • 使用所以我得到:“Observable”类型上不存在属性“超时”。
  • @NarendraVyas 尝试这样this.http.post(...).timeout(...).map(...)timeout 应该是第一个,然后是 .map(...)
  • 感谢@sebaferreras 现在我没有收到此错误,我还必须使用 import 'rxjs/add/operator/timeout';但我正在探索如何在出现错误时提醒用户刷新页面..再次感谢
【解决方案2】:

你可以这样做:

let returned = false;

startCallTime(slowConnectionLimit){
  setTimeout(() => {
    if(returned){
      // IS NOT SLOW
    } else {
      // IS SLOW. SHOW YOUR MESSAGE
    }
  }, slowConnectionLimit)
}

callApi = () => {
 startCallTime(30000); // WILL DETECT SLOW CONNECTION AFTER 30 SECONDS
 this.http.get().then((res) => {
    returned = true; // HERE YOU KNOW IF THE CALL HAS ENDED
 });
}

我认为@sebaferreras 的答案更干净,但只对 rxjs 有用...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多