无法阅读财产'导航'在angular2组件函数中未定义

时间:2016-12-12 15:28:35

标签: angular angular2-routing

我试图在倒计时之后导航。这是我的代码

 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

它做错了什么?

1 个答案:

答案 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);