簡體   English   中英

組件內的Angular 2路由不起作用(this.router.navigate不起作用)

[英]Angular 2 routing inside a component not working (this.router.navigate not working)

我試圖開發一個angular 2應用程序,一旦滿足特定條件,該應用程序將路由到另一個組件,為此,我使用了this.router.navigate方法,但它似乎沒有執行,因為它一直顯示“無法讀取屬性'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 + '%'; 
    }
  } 
}

}

錯誤

在此處輸入圖片說明

這是因為thisframe不再指向組件。 使用以下內容:

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

閱讀答案以及答案,以獲取更多信息以及使用bindbound class properties其他可能方法。

您可以存儲this到一個變量:

var that = this ;

在您可以用作的功能內

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

希望這可以幫助 :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM