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
.