我试图在倒计时之后导航。这是我的代码
constructor(
private router: Router
) {}
onsubmit(){
//I call the count down function here
this.countdown();
}
countDown() {
var i = 5;
var myinterval = setInterval(function() {
document.getElementById("countdown").innerHTML = "redirecting in: " + i;
if (i === 0) {
clearInterval(myinterval );
this.router.navigate(['/About']);
}
else {
i--;
}
}, 1000);
}
倒计时显示正常,但当它到达导航部分时, 我收到这个错误:
EXCEPTION: Cannot read property 'navigate' of undefined
它做错了什么?
答案 0 :(得分:12)
在Arrow function
函数中使用setInterval
,这将使this
函数中的组件``setInterval
(上下文)可用。
<强>代码强>
var myinterval = setInterval(() => { //<-- user arrow function
document.getElementById("countdown").innerHTML = "redirecting in: " + i;
if (i === 0) {
clearInterval(myinterval );
this.router.navigate(['/About']);
}
else {
i--;
}
}, 1000);