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

时间:2016-08-17 14:46:24

标签: angular typescript

我正在使用角度为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();
 }

谢谢!

3 个答案:

答案 0 :(得分:45)

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

首先,我在组件

中使用了beforeunload事件
@HostListener('window:beforeunload', ['$event'])
beforeunloadHandler(event) {
    this.endChat();
}

,其中

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

然后,诀窍是使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);
}

我能够使用

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

希望这有帮助!

答案 1 :(得分:19)

@HostListener('window:unload', ['$event'])
unloadHandler(event) {
  ...
}

另见javascript to check when the browser window is close

答案 2 :(得分:1)

现在,当浏览页面离开用户或关闭页面时,Chrome不允许在页面关闭期间执行同步XHR。

https://www.chromestatus.com/feature/4664843055398912

那么现在该怎么做才能对此事件进行同步调用。

相关问题