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?

3 Answers 3

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             
    }
  }
}
Sign up to request clarification or add additional context in comments.

4 Comments

Anyone care to comment why they down voted? Want to know what the problem is maybe I can fix it :)
My answer and the question were also downvoted, so I suspect someone just went through and blindly downvoted everything for some reason (the other answers hadn't been posted yet).
@Diopside has a point, if angular provides a way to listen for host events it is best to use that :)
it sees this, but I cannot make it see other variable defiuned before anonimous function. WIth php I just use use keyword and it is simple. How can it be so complicated in typescript?
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.

1 Comment

This works as well as the accepted answer, but Titan was first.
2

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

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

1 Comment

This works as well as the accepted answer, but Titan was first.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.