1

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

enter image description here

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

You can store this into a variable:

var that = this;

inside the function you can use as

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

Hope this helps :)

1 Comment

Thank you very much :), yours and Maximus answers did the trick :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.