Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot read property 'navigate' of undefined in an angular2 component function

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?

like image 244
Ericel Avatar asked Dec 12 '16 15:12

Ericel


1 Answers

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);
like image 126
Pankaj Parkar Avatar answered Oct 11 '22 18:10

Pankaj Parkar