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?
I tried with ngOnDestroy but for some reason the code is not being executed.
In my Component.ts I have.
import { Component, OnInit, AfterViewChecked, ElementRef, ViewChild,OnDestroy} from '@angular/core';
export class ChatComponent implements OnInit, AfterViewChecked,OnDestroy {
and finally
ngOnDestroy() {
this.endChat();
}
Thanks!
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!
@HostListener('window:unload', ['$event'])
unloadHandler(event) {
...
}
See also javascript to check when the browser window is close
Chrome now disallows synchronous XHR during page dismissal when the page is being navigated away from or closed by the user.
https://www.chromestatus.com/feature/4664843055398912
so now what to do to make synchronous calls on this event.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With