Angular 2 - Triggering code on window close

I am currently developing a chat application using Angular 2 and I have a question. How can I trigger the finish chat command to the backend when the user closes the chat window?

Within my component, I have a method that interacts with the backend service to end the chat session:


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

My concern is how can I automatically execute this code when the user closes the chat window? Is there a way to detect the closing event of the window?

I attempted to use ngOnDestroy within my Component.ts file but unfortunately, the code did not run as expected.


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

In order to address this issue, I added the following block of code:


ngOnDestroy() {
    this.endChat();
}

Your insights on this matter would be greatly appreciated!

Answer №1

Thank you to everyone who offered their assistance. I was able to develop a solution based on a different proposal.

Initially, I utilized the beforeunload event in the component:

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

in which

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

The key was to ensure that the http call was synchronous rather than asynchronous.

Prior to the modifications, the endchat method in the chat service appeared as follows:

    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 achieved success by implementing the following changes:

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

Hopefully, this explanation proves to be helpful!

Answer №2

@HostListener('window:beforeunload', ['$event'])
beforeUnloadHandler(event) {
  ...
}

Check out this resource on detecting when the browser window is about to close: javascript to check when the browser window is close

Answer №3

Google Chrome has implemented a policy to disallow synchronous XHR requests when a page is being navigated away from or closed by the user.

Learn more about this update here

Given this change, what are some alternative methods to make synchronous calls during this event?

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to retrieve an array that was created using the useEffect hook in React?

Utilizing the power of useEffect, I am fetching data from two different APIs to build an array. My goal is to access this array outside of useEffect and utilize it in the return statement below to render points on a map. However, when trying to access it ...

TypeScript NodeJS Error: Unable to access the 'address' property as it is undefined

Having just started using TypeScript, I am puzzled by the error it's throwing. The VanillaJS version works perfectly, but when I transferred it to TypeScript and checked my index.ts file, the same error persisted even after compiling the TS code usin ...

Expanding the Window Object in Typescript with Next.js Version 13

Within my Next.js 13 project, I am looking to enhance the Window object by adding a property called gtag I created an index.d.ts file in the root folder with the following content: index.d.ts declare module '*.svg' { const content: any; exp ...

Linking typescript error messages with their respective compiler configurations (tsconfig.json)

Is there a way to identify which compiler option corresponds to a specific Typescript error? While working with Typescript in VSCode, I often encounter errors like initializer provides no value for this binding element. (Please note that these are warnin ...

The element 'x' is implicitly bound with a type of 'any'

I've been exploring the world of Nextjs and TypeScript in an attempt to create a Navbar based on a tutorial I found (). Although I've managed to get the menu items working locally and have implemented the underline animation that follows the mou ...

Encountered a hiccup during the deployment of an Angular application on Heroku

I've been working on deploying an Angular app called "test-app" to Heroku via GitHub and everything seems to be going smoothly, except for setting up the express routing function. I've tried different paths, but Heroku keeps throwing this error: ...

angular2-mdl encountered a 404 error and could not be located

I have encountered a strange 404 error stating that the page is not found. Despite installing angular2-mdl using npm install angular2-mdl --save and confirming its presence in the node_modules directory, the error persists. Below is a snippet from my app. ...

Transferring variables between vanilla JS and Angular 2: A guide

I am facing a challenge where I need to retrieve an object title from vanilla JavaScript and then access it in my Angular 2 component. Currently, I am storing the variable in localStorage, but I believe there must be a better approach. The issue arises wh ...

What sets apart `import http = require('http');` from `import * as http from 'http';`?

After searching for a quality NodeJS with Typescript tutorial without success, I've decided to navigate this learning journey unassisted. However, I have encountered a question along the way. I'm confused about the distinction between these two ...

The Vue router fails to load when using create-vue@3

I've been experimenting with the Vue Router, but it's not giving me the expected outcome. While following the tutorial on https://router.vuejs.org/guide/, I found that if I use the CDN and place it in a standalone HTML file, it works fine. Howev ...

Importing DateTimeFormatOptions into Your Project

I have been trying to store a specific DateTimeFormatOptions for the date.toLocaleString() function so that I can easily use it in various parts of my application. Here is how I defined it: export const timeFormat = { month: 'numeric', day: &apos ...

When I declare a second service in the constructor, my modal service no longer opens as expected

Recently, I came across this login method in Angular: email: string = ""; password: string = ""; login() { const credentials = { email: this.email, password: this.password }; this.userService.login(credential ...

The correct way to update component state when handling an onChange event in React using Typescript

How can I update the state for 'selectedValues' in a React component called CheckboxWindow when the onChange() function is triggered by clicking on a checkbox? export const CheckboxWindow: React.FC<Props> = props => { const [selected ...

"Encountered an unhandled promise rejection related to the Select

I encountered an issue between my app.module.ts and my app.welcome-panel-menu-list.component.ts. Can someone help me identify the problem? app.module.ts: import { NgModule } from '@angular/core'; import { BrowserModule } from '@an ...

"Exploring the World of Websockets Using Ionic 3 and Angular

How can I successfully implement a Websocket in Ionic 3 and Angular 4? I attempted to use the socket.io-client package, but when I try to connect the websocket using the following code: this.socket = io(this.urls.websocket, {transports: ['websocket& ...

How can I extract a specific data value from a JSON file in Ionic 2?

Here is the JSON data: [ { "id": 1, "label": "saw", "total": "100" }, { "id": 2, "label": "saw1", "total": "300" }, { "id": 3, "label": "saw2", "total": "400" } ] Below is my Typescript code snippet: this. ...

Unable to configure Angular 2 tour of champions tutorial

When I accessed the Hero Editor page (https://angular.io/docs/ts/latest/tutorial/toh-pt1.html), I followed the given instructions: “Follow the setup instructions for creating a new project named angular-tour-of-heroes, after which the file structure sho ...

Incorporating JSON data into a reactive form group with nested objects and form arrays within nested components in Angular 13

After receiving JSON data from the backend and converting it into my model classes (which include nested classes and arrays), I encountered an issue while trying to create a reactive FormGroup by initializing it with my model class. The problem arose when ...

What is the best way to integrate Tawk.to into a React application while using typescript?

Having some issues integrating tawk.to into my website built with React and TypeScript. I have installed their official npm package, but encountered an error message: import TawkMessengerReact from '@tawk.to/tawk-messenger-react'; Could not fin ...

The parameter cannot be assigned a value of type 'string' as it requires a value that matches the format '`${string}` | `${string}.${string}` | `${string}.${number}`'

I recently updated my react-hook-forms from version 6 to version 7. Following the instructions in the migration guide, I made changes to the register method. However, after making these changes, I encountered the following error: The argument being pass ...