如何从匿名函数访问全局打字稿变量

myr*_*lav 2 typescript angular

我有一个 Angular2 应用程序,我想在用户关闭浏览器窗口时执行一些逻辑。我正在使用浏览器窗口的beforeunload事件。我在 TypeScript 类构造函数中放置了以下代码:

export class MyAngularComponent implements OnInit, OnDestroy {  

  callServer()
  {
     //Logic to call the server
  }

  constructor(private updateServiceFactory: UpdateService) {

    window.onbeforeunload = function(e){
      this.callServer();  //this does not work            
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

我在 this.callServer() 行中收到编译错误。错误显示“类型 'Window' 上不存在属性 'callServer'”。我知道匿名函数上下文中的“this”指的是 Window 对象。

问题:如何从匿名函数内部调用 callServer() 方法?

Tit*_*mir 5

使用箭头函数而不是简单的函数。箭头函数从声明上下文中捕获这一点。

export class MyAngularComponent implements OnInit, OnDestroy {  

  callServer()
  {
     //Logic to call the server
  }

  constructor(private updateServiceFactory: UpdateService) {

    window.onbeforeunload = (e) => {
      this.callServer();  //this now refers to MyAngularComponent             
    }
  }
}
Run Code Online (Sandbox Code Playgroud)