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?