简体   繁体   中英

set timeout for http request in ionic1 with angularjs

I'm making an HTTP call in a controller in my ionic1 app. there are times the internet connection is slow and I'd like to put a timeout on the scripts. For example, when there is no response for 20 seconds an alert should pop up

.controller('account_statement_ctrl', function($scope, $http, $ionicLoading, $ionicPopup, $cordovaToast, $location, $ionicModal, $filter) {
  $scope.account_number = localStorage.getItem("account_number");
  ///alert if connection fails
  $scope.connect = function() {
    var alertPopup = $ionicPopup.alert({
      title: 'Error',
      template: '<p align="center">Internet Connectivity Problem</p>',
    });
  };


  $scope.nobill = function() {
    var alertPopup = $ionicPopup.alert({
      title: 'Error',
      template: '<p align="center">Not Found</p>',
    });
  };

  $scope.acc_request = function() {

    $scope.start_date = $filter('date')($scope.sdate, "yyyy-MM-dd");
    $scope.end_date = $filter('date')($scope.edate, "yyyy-MM-dd");

    $ionicLoading.show({
      template: '<p>Processing Request</p><ion-spinner></ion-spinner>'
    });
    $http.get("http://localhost/app/state?account_number=" + $scope.account_number).success(function(data) {
      $scope.statement = data.data
        //console.log(JSON.stringify(data.data))
        {
          $ionicLoading.hide();
        }
    })
  }
})

$http.get returns a Promise which can either call a success or error callback. You can set the timeout on the request (seedocs ) and then react to the timeout in the error callback.

$http.get(myUrl, { timeout: 20000 }).then(successCallback, errorCallback);

Read the general documentation for more details.

BTW in your script you're using .success which is deprecated. The advised way is to use standardized Promise API, ie .then() .

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