gpt4 book ai didi

Angular 2 - 关闭窗口时执行代码

转载 作者:太空狗 更新时间:2023-10-29 16:50:45 24 4
gpt4 key购买 nike

我正在使用 Angular 2 开发聊天应用程序。

如何在用户关闭窗口时将结束聊天命令发送到后端?

我的组件有一个调用后端服务以如下方式结束聊天的方法

 endChat() {
this.chatService.endChat(this.chatSessionInfo).subscribe(
result => this.OnGetMessages(result),
error => this.OnChatEndError(error)
);
}

关闭窗口时如何执行该代码?如何检测窗口关闭事件?

我尝试使用 ngOnDestroy 但由于某种原因代码没有被执行。

在我的 Component.ts 中我有。

import { Component, OnInit, AfterViewChecked, ElementRef, ViewChild,OnDestroy} from '@angular/core';

export class ChatComponent implements OnInit, AfterViewChecked,OnDestroy {

最后

 ngOnDestroy() { 
this.endChat();
}

谢谢!

最佳答案

感谢大家的帮助。我能够根据不同的提案创建解决方案。

首先我在组件中使用了beforeunload事件

@HostListener('window:beforeunload', ['$event'])
beforeunloadHandler(event) {
this.endChat();
}

在哪里

endChat() {
this.chatService.endChatSync(this.chatSessionInfo);
}

然后,诀窍是让 http 调用同步而不是异步。

之前聊天服务端的endchat方法是

    endChat(chatSessionInfo: ChatSessionInfo)  : Observable<ChatTranscription> {
console.log("Ending chat..");
let body = JSON.stringify(chatSessionInfo);
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.delete(this.apiUrl + "Chat?userId="+chatSessionInfo.UserId+"&secureKey="+chatSessionInfo.SecureKey,options)
.map(this.extractData)
.catch(this.handleError);
}

我能够让它工作

endChatSync(chatSessionInfo: ChatSessionInfo)  {
console.log("Ending chat..");
let xhr = new XMLHttpRequest()
xhr.open("DELETE",this.apiUrl +"Chat?userId="+chatSessionInfo.UserId+"&secureKey="+chatSessionInfo.SecureKey,false);
xhr.send();
}

希望这对您有所帮助!

关于Angular 2 - 关闭窗口时执行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38999842/

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