Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
412 views
in Technique[技术] by (71.8m points)

typescript - Angular 2 - Execute code when closing window

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)
        );
    }
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

First I used the beforeunload event in the component

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

where

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

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

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

I was able to make it work with

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

Hope this helps!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...