$ http.post超时无法正常工作

时间:2017-09-10 02:06:26

标签: javascript jquery angularjs ionic-framework

我在$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秒,则不应触发警报。

1 个答案:

答案 0 :(得分:0)

我刚刚添加了一个布尔变量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();


                });
    }
});
相关问题