简体   繁体   中英

Timeout in $http.post not working properly

I've added a timeout on my $http.post . The reason is, when $http.post is called then it will communicate to the $htt.post(url.com) and if timeout is reached then it should stop the request of the url. Here's my code:

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

As we can see, I set the timeout into 40seconds. Everytime the $http.post request is executed and it meets the 40seconds it will alert the alert("Process stopped") which is fine! But my problem is, when the request $http.post is executed less than 40seconds it still alerts the alert("Process stopped!") which should not be fired. Please help me. The alert should not be fired if the request is less than 40 seconds.

I just added a variable isCompleted which is boolean.

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


                });
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM