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

查看:35
本文介绍了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天全站免登陆