加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 06:53:38 所属栏目:安全 来源:网络整理
导读:我试图在一些倒计时之后导航.这是我的代码 constructor( private router: Router ) {}onsubmit(){ //I call the count down function here this.countdown(); }countDown() { var i = 5; var myinterval = setInterval(function() { document.getElementById
我试图在一些倒计时之后导航.这是我的代码

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读