Angular 2 组件内部的路由不起作用(this.router.navigate 不起作用)
Angular 2 routing inside a component not working (this.router.navigate not working)
我正在尝试开发一个 angular 2 应用程序,一旦满足特定条件,它就会路由到不同的组件,为此我使用了 this.router.navigate 方法,但它似乎没有执行,因为它一直显示 "Cannot read property 'navigate' of undefined" 错误。将不胜感激 :)
具体组件
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 + '%';
}
}
}
}
错误
因为this
中的frame
不再指向组件。使用以下内容:
var id = setInterval(()=>{ frame() }, 20);
阅读 and this 答案以获取更多信息和使用 bind
和 bound class properties
的其他可能方法。
您可以将 this
存储到一个变量中:
var that = this
;
在您可以使用的函数内 as
that.router.navigate(['/details']);
希望这对您有所帮助:)
我正在尝试开发一个 angular 2 应用程序,一旦满足特定条件,它就会路由到不同的组件,为此我使用了 this.router.navigate 方法,但它似乎没有执行,因为它一直显示 "Cannot read property 'navigate' of undefined" 错误。将不胜感激 :)
具体组件
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 + '%';
}
}
}
}
错误
因为this
中的frame
不再指向组件。使用以下内容:
var id = setInterval(()=>{ frame() }, 20);
阅读 bind
和 bound class properties
的其他可能方法。
您可以将 this
存储到一个变量中:
var that = this
;
在您可以使用的函数内 as
that.router.navigate(['/details']);
希望这对您有所帮助:)