I have an Angular 4 applicaton and I want to call the logout function when the user close the page (window or tab of the browser).
This is my logout function :
let currentUser: User = JSON.parse(localStorage.getItem('currentUser'));
let headers = new Headers({ 'Authorization': 'Basic ' + btoa(currentUser.login + ":" + currentUser.password),
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'access-control-allow-headers, access-control-allow-origin, content-type, authorization'
});
let opts = new RequestOptions();
opts.headers = headers;
return this.http.get(this.route + 'UserLogout', opts).map((response: Response) => response.json());
}
And in my app.component.ts, I have :
@HostListener('window:beforeunload', ['$event'])
beforeUnloadHander(event) {
this.authenticationService.logoutOnClose().subscribe(res=> {
localStorage.removeItem('currentUser');
});
}
But the window is close and the request is never done. I think I need to do the request synchronously but I don't know how to do it.
Do you have an idea ?
EDIT
I tried with jQuery :
ngOnDestroy(){
let currentUser: User = JSON.parse(localStorage.getItem('currentUser'));
$.ajax({ url: 'myURL',
beforeSend: function(request) {
request.setRequestHeader("Authority", '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) {
alert('test');
localStorage.removeItem('currentUser');
}, async: false });
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…