我正试图在ng2中找到路由,我遇到了一个奇怪的问题。当用户到达'/ home'时,我试图设置超时以将我导航回'/'。
这有效:
export class HomeComponent implements OnInit {
constructor(private router: Router) { }
ngOnInit() {
setTimeout(() => {this.router.navigate(['/']);}, 2000);
}
}
但这不是:
export class HomeComponent implements OnInit {
constructor(private router: Router) { }
ngOnInit() {
setTimeout(function () {this.router.navigate(['/']);}, 2000);
}
}
它失败了 - EXCEPTION: Cannot read property 'navigate' of undefined
为了使其有效,我必须将其更改为:
export class HomeComponent implements OnInit {
constructor(private router: Router) { }
ngOnInit() {
var _router = this.router;
setTimeout(function (_router) {_router.navigate(['/']);}, 2000, _router);
}
}
顺便说一下,这是TypeScript编译() => {}
的方式。但是,它不知道第二个代码段中的this
在setTimeout()中不可用吗?这是TypeScript的限制吗?
答案 0 :(得分:5)
对于Typescript,这个是Object,它在Angular 1.x中表示为$ scope变量。如果您在Types of Typescript逻辑中编写本机JavaScript,那么它会将 this 视为 window 对象。因此,您将无法再访问typescript对象此。
为了克服这个问题,每当您使用JavaScript代码时,我都会有一个简单的想法:
export class HomeComponent implements OnInit {
constructor(private router: Router) { }
ngOnInit() {
let that = this; // Assign scope variable to temporary variable: that
setTimeout(function () {that.router.navigate(['/']);}, 2000); // Use that particular variable anywhere in the method scope instead of Scope variable
}
}
注意: Typescript不鼓励您在代码中使用JavaScript。因为ts linting已经在生成JavaScript输出。但是如果你想使用JavaScript,那么这是唯一的解决方案。