gpt4 book ai didi

angular - 在 Angular 4 中关闭窗口时注销

转载 作者:太空狗 更新时间:2023-10-29 18:15:32 25 4
gpt4 key购买 nike

我有一个 Angular 4 应用程序,我想在用户关闭页面(浏览器的窗口或选项卡)时调用注销函数。

这是我的注销功能:

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

在我的 app.component.ts 中,我有:

@HostListener('window:beforeunload', ['$event'])
beforeUnloadHander(event) {
this.authenticationService.logoutOnClose().subscribe(res=> {
localStorage.removeItem('currentUser');
});

}

但窗口已关闭,请求从未完成。我想我需要同步执行请求,但我不知道该怎么做。

你有什么想法吗?

编辑我尝试使用 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 });
}

最佳答案

我找到了方法。所以,我宁愿避免使用 Angular 的 jQuery,但像 Sriram Jayaraman 一样,我没有找到任何其他方法来解决我的问题。但是函数 @HostListener('window:beforeunload')@HostListener('window:onunload') 不工作。

因此,在我的 app.component.ts 的 ngOnInit 中,我为 beforeunload 添加了一个事件监听器到窗口,如果用户已连接,我将调用一个函数来进行 ajax 调用。

这是我的代码:

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

关于angular - 在 Angular 4 中关闭窗口时注销,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47199361/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com