I'm trying to get a hang of routing in ng2 and I faced a strange issue. I tried to set a timeout to navigate me back to '/' when a user reaches '/home'.
This works:
export class HomeComponent implements OnInit {
constructor(private router: Router) { }
ngOnInit() {
setTimeout(() => {this.router.navigate(['/']);}, 2000);
}
}
But this does not:
export class HomeComponent implements OnInit {
constructor(private router: Router) { }
ngOnInit() {
setTimeout(function () {this.router.navigate(['/']);}, 2000);
}
}
It fails with - EXCEPTION: Cannot read property 'navigate' of undefined
To make it work, I have to change it to:
export class HomeComponent implements OnInit {
constructor(private router: Router) { }
ngOnInit() {
var _router = this.router;
setTimeout(function (_router) {_router.navigate(['/']);}, 2000, _router);
}
}
Incidentally, this is how TypeScript compiles () => {}
into. But does it not know that this
is not available within setTimeout() in the second code snippet? Is this a limitation of TypeScript?