组件内的Angular 2路由无法正常工作(this.router.navigate无效)

时间:2017-07-31 04:53:15

标签: javascript angular router

我正在尝试开发一个角度2应用程序,一旦满足特定条件就会路由到不同的组件,为此我使用了this.router.navigate方法,但它似乎没有执行,因为它一直显示“无法读取属性“导航”未定义的“错误。将不胜感激任何帮助:)

特定组件

import { Component, OnInit } from '@angular/core';

import { RouterModule, Routes, Router } from '@angular/router';

@Component({
  selector: 'app-searching',
  templateUrl: './searching.component.html',
  styleUrls: ['./searching.component.css']
})
export class SearchingComponent implements OnInit {

constructor(private router:Router) { }

ngOnInit() {
 var elem = document.getElementById("rightSideMovingProgressBar"); 
 var elem2 = document.getElementById("progressText");
 var height = 100;
 var height2 = 0;
 var id = setInterval(frame, 20);
 function frame() {
    if (height <= 0) {
        clearInterval(id);
        this.router.navigate(['/details']);
    } else {
        height--;
        height2++; 
        elem.style.height = height + 'vh';
        elem2.innerHTML = height2 + '%'; 
    }
  } 
}

}

错误

enter image description here

2 个答案:

答案 0 :(得分:3)

这是因为this中的frame不再指向该组件。使用以下内容:

 var id = setInterval(()=>{ frame() }, 20);

阅读thisthis个答案,了解有关使用bindbound class properties的更多信息和其他可能方法。

答案 1 :(得分:1)

您可以将this存储到变量中:

var that = this;

你可以用作

的功能

that.router.navigate(['/details']);

希望这会有所帮助:)

相关问题