如果 angularJs 中的请求超过 30 秒,如何显示警报?
How to display alert if request is longer than 30 sec in angularJs?
有时一个请求花费的时间太长,我想在这种情况下显示一些警报或toastr。知道如何赶上请求时间吗?提前致谢
您可以使用承诺$q
,因为承诺只能解决一次,并且在被拒绝后无法解决。在此示例中,使用输入指定请求完成之前的等待时间(以秒为单位)。如果届时请求尚未完成,则会在 5 秒后显示警报。
angular.module("app", [])
.controller("ctrl", function($scope, $timeout, $q) {
$scope.wait = 0;
$scope.request = function() {
const timer = $q.defer();
timer
.promise
.then(function(value) {
alert(value);
})
// do nothing
.catch(() => {});
$timeout(function() {
timer.resolve("Request takes too long");
}, 5000);
$timeout(function() {
// Here your request resolves successfully
console.log("Resolving request");
timer.reject();
}, $scope.wait * 1000);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.js"></script>
<div ng-app="app" ng-controller="ctrl">
<input type="number" ng-model="wait">
<button ng-click="request()">Click</button>
</div>
有时一个请求花费的时间太长,我想在这种情况下显示一些警报或toastr。知道如何赶上请求时间吗?提前致谢
您可以使用承诺$q
,因为承诺只能解决一次,并且在被拒绝后无法解决。在此示例中,使用输入指定请求完成之前的等待时间(以秒为单位)。如果届时请求尚未完成,则会在 5 秒后显示警报。
angular.module("app", [])
.controller("ctrl", function($scope, $timeout, $q) {
$scope.wait = 0;
$scope.request = function() {
const timer = $q.defer();
timer
.promise
.then(function(value) {
alert(value);
})
// do nothing
.catch(() => {});
$timeout(function() {
timer.resolve("Request takes too long");
}, 5000);
$timeout(function() {
// Here your request resolves successfully
console.log("Resolving request");
timer.reject();
}, $scope.wait * 1000);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.js"></script>
<div ng-app="app" ng-controller="ctrl">
<input type="number" ng-model="wait">
<button ng-click="request()">Click</button>
</div>