2017-09-10 94 views
-1

我在我的$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秒,則不應觸發警報。

+0

您需要檢查請求是否已完成,然後再嘗試取消它。 BTW調試使用'alert()'不好,因爲它會停止進程。更好地使用console.log或者更好的是npm'debug'模塊 – Mikkel

+0

你的意思是什麼? @Mikkel – user8143979

+0

哪部分你不清楚?你的回答表明你已經接受了船上的建議 – Mikkel

回答

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


       }); 
    } 
});