如何从匿名函数访问全局typescript变量

时间:2017-08-24 21:25:56

标签: angular typescript

我有一个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            
    }
  }
}

我在this.callServer()行中收到编译错误。该错误表示"属性' callServer'类型' Window'"上不存在。我明白了这个"这个"在匿名函数的上下文中引用Window对象。

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

3 个答案:

答案 0 :(得分:4)

尝试在组件中使用HostListener,而不是在构造函数中使用。

 @HostListener('window:beforeunload', ['$event'])
 doSomething($event) {
     // your code here //
 }

除了与传递给构造函数的参数直接相关的东西之外,构造函数通常不是做任何事情的好地方。

答案 1 :(得分:2)

使用箭头功能而不是简单的功能。箭头函数从声明的上下文中捕获它。

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             
    }
  }
}

答案 2 :(得分:2)

您可以使用bind将函数的this更改为正确的上下文。

window.onbeforeunload = function(e){
  this.callServer();
}.bind(this)