我正在 ionic1 应用程序的 Controller 中进行 HTTP 调用。有时互联网连接速度很慢,我想在脚本上设置超时。例如,当 20 秒内没有响应时,应弹出警报
.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
返回一个 Promise
,它可以调用 success
或 error
回调。您可以在请求上设置超时(请参阅 docs ),然后在 error
回调中对超时使用react。
$http.get(myUrl, { timeout: 20000 }).then(successCallback, errorCallback);
阅读general documentation了解更多详情。
顺便说一句,在您的脚本中,您使用的是 .success
已弃用。
建议的方法是使用标准化的 Promise API,即 .then()
。
关于javascript - 使用angularjs在ionic1中为http请求设置超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46765677/