Angular 2-关闭窗口时执行代码 [英] Angular 2 - Execute code when closing window

查看:57
本文介绍了Angular 2-关闭窗口时执行代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用angular 2开发聊天应用程序.

I am working on a chat application using angular 2.

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

How can i send the finish chat command to the backend when the user closes the window?

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

My component has a method that calls the backend service to end the chat in the following way

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

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

How can i execute that code when closing the window? How can i detect the window close event?

我尝试使用ngOnDestroy,但是由于某些原因,代码未执行.

I tried with ngOnDestroy but for some reason the code is not being executed.

在我的Component.ts中.

In my Component.ts I have.

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

export class ChatComponent implements OnInit, AfterViewChecked,OnDestroy  {

最后

 ngOnDestroy() { 
    this.endChat();
 }

谢谢!

推荐答案

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

Thanks everyone for the help. I was able to create a solution based on different proposal.

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

First I used the beforeunload event in the component

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

其中

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

然后,诀窍是使http通话不同步.

Then, the trick is to make the http call sync not async.

之前,聊天服务中的endchat方法是

Before, the endchat method at the chat service was

    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-关闭窗口时执行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆