Logout when closing window in Angular 4

I found how to do it. So, I would prefer avoid jQuery with Angular but like Sriram Jayaraman I didn't find anything else to fix my problem. But the functions @HostListener('window:beforeunload') and @HostListener('window:onunload') are not working.

So, in the ngOnInit of my app.component.ts, I added an event listener for beforeunload to the window and if the user is connected I call a function which make an ajax call.

This is my code :

ngOnInit() {
    let context = this;
    window.addEventListener("beforeunload", function (e) {
        let currentUser : User = JSON.parse(localStorage.getItem('currentUser'));
        if(currentUser){
            context.logoutOnClose();
        }
    });
}

logoutOnClose(){
    let currentUser: User = JSON.parse(localStorage.getItem('currentUser'));
    $.ajax({ url: 'myURL',
    beforeSend: function(request) {
        request.setRequestHeader("Authorization", 'Basic ' +  btoa(currentUser.login + ":" + currentUser.password));
        request.setRequestHeader('Content-Type', 'application/json');
        request.setRequestHeader('Access-Control-Allow-Origin', '*');
        request.setRequestHeader('Access-Control-Allow-Headers', 'access-control-allow-headers, access-control-allow-origin, content-type, authorization');
    },
    type: 'GET',
        success: function (result) {
        localStorage.removeItem('currentUser');
    },
    async: false });
}

You can store your user and credentials in sessionStorage rather than localStorage. sessionStorage is removed whenever you close tab/browser, localStorage don't !