无法在angular2组件函数中读取undefined的属性’navigate’

前端之家收集整理的这篇文章主要介绍了无法在angular2组件函数中读取undefined的属性’navigate’前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图在一些倒计时之后导航.这是我的代码

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

它做错了什么?

解决方法

在setInterval函数中使用箭头函数,这将使得setInterval函数中的Component“this(context)可用.

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

猜你在找的Angularjs相关文章