2

I have an Angular2 application and I want to perform some logic when the user closes the browser window. I am using beforeunload event of the browser window. I have placed the following code in my TypeScript class constructor:

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

I am getting the compile error in the line this.callServer(). The error says "Property 'callServer' does not exist on type 'Window'". I understand that "this" in the context of the anonymous function refers to the Window object.

Question: how do I call callServer() method from inside of the anonymous function?

myroslav
  • 1,670
  • 1
  • 19
  • 40

3 Answers3

8

Use an arrow function instead of a simple function. Arrow functions capture this from the declaring context.

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             
    }
  }
}
Titian Cernicova-Dragomir
  • 230,986
  • 31
  • 415
  • 357
4

Try using HostListener in your component, and not in the constructor.

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

The constructor is usually not a good place to do anything other than stuff directly related to parameters passed into the constructor.

diopside
  • 2,981
  • 11
  • 23
2

You can use bind to change the function's this to the correct context.

window.onbeforeunload = function(e){
  this.callServer();
}.bind(this)
John Montgomery
  • 6,739
  • 9
  • 52
  • 68