2017-07-31 226 views
1

我试图开发一个角度2应用程序,路由到不同的组件,一旦满足特定的条件,为此我使用this.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

回答

3

这是因为thisframe不再指向组件。使用以下命令:

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

阅读thisthis答案使用bindbound class properties的更多信息以及其他可能的方法。

1

可以存储this到一个变量:

var that = this;

里面的功能,你可以使用如

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

希望这有助于:)

+0

非常感谢你:),你和马克西姆斯答案的伎俩:) –