Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 966
federom Avatar asked Aug 17 '16 14:08

federom


3 Answers

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!

like image 142
federom Avatar answered Nov 07 '22 06:11

federom


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

See also javascript to check when the browser window is close

like image 33
Günter Zöchbauer Avatar answered Nov 07 '22 06:11

Günter Zöchbauer


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.

like image 2
Vivek Joshi Avatar answered Nov 07 '22 07:11

Vivek Joshi