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?
() => {}is an ECMAScript 6 Arrow Function: "An arrow function expression has a shorter syntax than a function expression and does not bind its own this, arguments, super, or new.target. Arrow functions are always anonymous. These function expressions are best suited for non-method functions, and they cannot be used as constructors." The changes works because there is no reliance onthis.thisfrom their surrounding scope, while old-style functions don't inheritthisfrom their surrounding scope. The difference is important because of the "this" problem withsetTimeout.