我正在使用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) { ... }
事件来取消承诺,但这样我需要保存intervalPromise
变量并且...它看起来太有线了!有没有更好的方法以直接的方式实现这个倒计时逻辑?
答案 0 :(得分:2)
首先使用$timeout
而非$interval
用于此
为什么存储承诺似乎过于有线?当然你需要将它存储在某个地方以便稍后调用它:这是我将如何做到的:
var promise = $timeout(function(){
// your code
promise = null;
//perform redirect
}, 10000);
$scope.$on("$routeChangeSuccess", function (args) {
if(promise != null){
$timeout.cancel(promise);
}
};