【问题标题】:Timeout in $http.post not working properly$http.post 中的超时无法正常工作
【发布时间】:2018-02-18 13:43:45
【问题描述】:

我在$http.post 上添加了超时。原因是,当调用$http.post 时,它将与$htt.post(url.com) 通信,如果达到超时,则它应该停止对url 的请求。这是我的代码:

var canceler = $q.defer();
$http.post('www.example.com/api',{
    //some json data
}, {timeout: canceler.promise}).then(function(response){
    alert("Success");
});

// the timeout
$timeout(function(){
    $rootScope.$apply(function(){
        canceler.resolve();
        alert("Process stopped!");
    });
}, 40000);

如我们所见,我将超时设置为 40 秒。每次执行$http.post 请求并且满足 40 秒时,它都会提醒alert("Process stopped"),这很好!但我的问题是,当请求 $http.post 执行不到 40 秒时,它仍然会提醒不应触发的 alert("Process stopped!")。请帮我。如果请求少于 40 秒,则不应触发警报。

【问题讨论】:

  • 您需要在尝试取消之前检查请求是否已完成。 BTW 调试使用 alert() 不好,因为它会停止进程。更好地使用 console.log 或者更好地使用 npm debug 模块
  • 你是什么意思? @Mikkel
  • 你不清楚哪一部分?您的回答表明您已采纳建议

标签: javascript jquery angularjs ionic-framework


【解决方案1】:

我刚刚添加了一个布尔变量isCompleted

var isCompleted = false;
$http.post('url',{
  // datas
},{timeout:canceler.promise}).then(function(){
  // request completed
  isCompleted = true;
});

$timeout(function(){
    if(isCompleted == true){
       // Do nothing because already completed the request
    }else{
       // timeout of 40 seconds is reached. Notify User

            $rootScope.$apply(function(){
            $ionicPopup.alert({
                        title: 'Oops, Something went wrong!',
                        template: 'It looks like that you\'re not connected to the internet or you have  a poor connection.'
                    });
                    canceler.resolve();


                });
    }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-30
    • 2021-05-23
    • 1970-01-01
    • 2014-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-20
    相关资源
    最近更新 更多