Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

http - Logout when closing window in Angular 4

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...