2017-07-31 121 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

非常感謝你:),你和馬克西姆斯答案的伎倆:) –