I am trying to navigate after some count down. Here is my code
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);
}
The count down displays fine but when it gets to the navigate part, I get this error :
EXCEPTION: Cannot read property 'navigate' of undefined
What is it am doing wrong?
Use Arrow function
in setInterval
function, which would make Component `` this
(context) available inside setInterval
function.
Code
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With