简体   繁体   中英

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

Im trying to develop an angular 2 app that routes to a different component once a specific condition is met, for this i used the this.router.navigate method but it doesnt seem to execute as it keeps showing the "Cannot read property 'navigate' of undefined" error. will appreciate any help on this :)

The specific component

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 + '%'; 
    }
  } 
}

}

The error

在此处输入图片说明

It's because this in the frame is no longer points to the component. Use the following:

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

Read this and this answers for more information and other possible approaches using bind and bound class properties .

You can store this into a variable:

var that = this ;

inside the function you can use as

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

Hope this helps :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM