打字稿:'()=> {}'不是'function(){}'的替代品吗?

Ste*_*rex 0 javascript this typescript angular

我试图在ng2中找到路由,我遇到了一个奇怪的问题.当用户到达'/ home'时,我尝试设置超时以将我导航回'/'.

这有效:

export class HomeComponent implements OnInit {

    constructor(private router: Router) { }

    ngOnInit() {
        setTimeout(() => {this.router.navigate(['/']);}, 2000);
    }

}
Run Code Online (Sandbox Code Playgroud)

但这不是:

export class HomeComponent implements OnInit {

    constructor(private router: Router) { }

    ngOnInit() {
        setTimeout(function () {this.router.navigate(['/']);}, 2000);
    }

}
Run Code Online (Sandbox Code Playgroud)

它失败了 - 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);
    }

}
Run Code Online (Sandbox Code Playgroud)

顺便说一句,这是TypeScript编译的方式() => {}.但它不知道this在第二个代码片段中的setTimeout()中不可用吗?这是TypeScript的限制吗?

Kru*_*nal 5

对于Typescript,是Object,它在Angular 1.x中表示为$ scope变量.如果您在打字稿逻辑的范围写本地JavaScript则其会考虑这个作为一个窗口对象.所以,你将不能访问打字稿对象这个了.

为了解决这个问题,每当您使用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
   }
}
Run Code Online (Sandbox Code Playgroud)

注意: Typescript不鼓励您在代码中使用JavaScript.因为ts linting已经在生成JavaScript输出.但是如果你想使用JavaScript,那么这是唯一的解决方案.