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

fed*_*rom 28 typescript angular

我正在使用角度2进行聊天应用程序.

当用户关闭窗口时,如何将完成聊天命令发送到后端?

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

 endChat() {
        this.chatService.endChat(this.chatSessionInfo).subscribe(
            result => this.OnGetMessages(result),
            error => this.OnChatEndError(error)
        );
    }
Run Code Online (Sandbox Code Playgroud)

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

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

在我的Component.ts中我有.

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

export class ChatComponent implements OnInit, AfterViewChecked,OnDestroy  {
Run Code Online (Sandbox Code Playgroud)

最后

 ngOnDestroy() { 
    this.endChat();
 }
Run Code Online (Sandbox Code Playgroud)

谢谢!

fed*_*rom 53

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

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

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

哪里

endChat() {
    this.chatService.endChatSync(this.chatSessionInfo);
}
Run Code Online (Sandbox Code Playgroud)

然后,诀窍是使http调用同步不是异步.

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

    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);
}
Run Code Online (Sandbox Code Playgroud)

我能够使它工作

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();
}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!

  • Have you tested `new XMLHttpRequest()` in all browsers? (3认同)

Gün*_*uer 20

@HostListener('window:unload', ['$event'])
unloadHandler(event) {
  ...
}
Run Code Online (Sandbox Code Playgroud)

另请参阅javascript以检查浏览器窗口何时关闭

  • `@HostListener('window:unload',['$ event'])`对我来说不起作用(Angular2 v2.4.6)通过设置`e.returnValue`来显示确认对话框.然而,`@HostListener('window:beforeunload',['$ event'])`的作用是什么. (2认同)