我正在使用ngRoute
模块来处理angularJS单页应用程序中的多个链接。有时,用户到达错误的链接并应重定向(因为内容是动态的,因此取决于外部来源,但无关紧要)。
假设我想在10秒后重定向用户,同时我想显示警告并显示倒计时。我只是使用从形式10开始的seconds
变量和具有$interval
的秒数直到0的函数,然后重定向
$scope.seconds = 10;
$scope.startCountdown = function () {
var intervalPromise = $interval(function () {
if ($scope.seconds > 0) {
$scope.seconds--;
}
else {
$interval.cancel(intervalPromise);
$location.search({});
$location.path("/");
}
}, 1000);
}
$scope.startCountdown();
它可以正常工作,但是当用户在倒数计时完成之前更改位置(他可以从顶部菜单调用
$location.path("/Summary")
)时,倒数计时仍在后台进行,几秒钟后便被重定向到首页。我该如何解决?我可以使用
$scope.$on("$routeChangeSuccess", function (args) { ... }
事件来取消promise,但是那样的话,我需要保存intervalPromise
变量,并且...似乎太有线了!有没有更好的方法可以直接实现这种倒数逻辑? 最佳答案
首先为此使用$timeout
而不是$interval
为什么为什么存储诺言似乎太有线了?当然,您需要将其存储在某个地方以便以后调用:这是我的处理方式:
var promise = $timeout(function(){
// your code
promise = null;
//perform redirect
}, 10000);
$scope.$on("$routeChangeSuccess", function (args) {
if(promise != null){
$timeout.cancel(promise);
}
};