Guide to invoking the API prior to shutting down the browser window in Angular4

Currently, I am working on an Angular 4 application that consists of 5 components. My goal is to trigger an API call when the user closes the browser window from any one of these components.

However, I have encountered an issue where the API does not get called when I close the application.

In my app.component.ts file, I have the following code:


export class AppComponent implements OnInit {

    constructor(private CartdataService: CartdataService, private http: HttpClient) { }

    ngOnInit() {}

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

    WindowClosed() {
        this.CartdataService.get_DummyCall().subscribe();
    }
}

As of now, I have only implemented the above code and I am unsure of what mistakes I may have made. Can anyone provide insight into where I might be going wrong?

For additional reference, you can visit the following link: Angular 2 - Execute code when closing window

Answer №1

Success! The solution is now in hand.

@HostListener('window:beforeunload', ['$event'])
    public beforeunloadHandler($event) {
    this.CartdataService.get_DummyCall().subscribe();
   }

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

The battle of environmental impact versus utility value in the realm of constants

Imagine having a collection of links that you want to organize in a separate file like this: export const SITE_LINKS = [ { text: 'About', path: '/about' }, { text: 'Projects', path: '/projects} ] You plan to utiliz ...

What is the best way to generate a JSON object with Angular and showcase its content through HTML?

Currently, I am dealing with a JSON object that is completely unfamiliar to me. Without knowing the keys or values of this object, I was able to successfully manipulate it and extract the necessary information. Ultimately, I have generated an array (whic ...

Function in Typescript used for checking types and catching compilation errors from external sources

Fact: I am currently using TS version 2.3.4. I have developed a function that checks if a variable is defined (it takes the parameter variable and returns 'undefined' !== typeof variable). It's quite simple. export function IsDefined(variab ...

Considering the move from AngularJS 1.4 to Angular 8 is a significant one, the question arises: should one opt to migrate to 1.5 before upgrading

After conducting extensive research, I am still unsure of the best approach for migrating a large, poorly structured program to Angular 8 (or at least Angular 7). The options of vertical slicing, horizontal slicing, or a complete rewrite all seem dauntin ...

Angular2 - Implementing Form Validation for Dynamically Generated Input Fields Based on Conditions

My goal is to create a basic form that allows users to select between two options: Local and Foreigner. If the user does not make a selection, the form should be marked as invalid. Choosing Local will make the form valid, while selecting Foreigner will rev ...

Replicate the process of transferring table rows to the clipboard, but exclusively copying the contents

Currently, I am attempting to copy a paginated table to my clipboard by referring to this guide: Select a complete table with Javascript (to be copied to clipboard). However, the issue lies in the fact that it only copies the data from the first page. In ...

Installing failed due to an error in the postinstall script of @angular/core version 9

I'm at the beginning of my coding journey and I am looking to set up a source code on my computer. node -v v12.16.1 npm -v 6.13.4 Could you assist me in resolving this issue that arises when I try to run the npm install command (on Windows 7 ...

Angular 4 animation issue: duration of transitions not being properly implemented

Why isn't the transition working as expected? Even though the animate function is set with a time of 2 seconds, the transition happens instantly. trigger('showMenu', [ state('active', style({ marginLeft: '0px' }) ...

The function signature '() => Element' is incompatible with the type 'string'

Greetings! I have a standard function that returns a span with a prop (if I'm not mistaken). In my TS code, I am encountering this error: Error image Below is the code from the file named qCard.tsx: import { QuestionAnswerTwoTone } from "@material- ...

Best practices for utilizing ngrx/store in Angular 2

As I am refactoring my Angular 2 applications to follow the ngrx pattern, some questions have arisen in my mind: My application retrieves a list of apps and a list of app categories. Can I manage state like "selectedCategory" (where only one can be select ...

Facing numerous "error TS1005" messages when performing a gulp build due to node_modules/@types/ [prop types] and [react] index.d.ts with SPFx Webpart

I am currently in the process of developing a custom spfx webpart that includes a feature to display link previews. In order to achieve this functionality, I integrated this specific library. However, I encountered some challenges during the implementation ...

Select hours using the PrimeNG slider feature

Is there a way to customize the PrimeNG slider in order to allow for selecting a time interval? I would like the slider to default to 12:00 when the user opens the application, but also be able to extend the selection range from 00:00 to 23:59. It seems ...

Filtering posts in Angular with the use of pipes

I've been attempting to use pipes in Angular to filter posts from a table, but I keep running into this error on the console: core.js:12689 Can't bind to 'ngForFilter' since it isn't a known property of 'a'. I believe th ...

Exploring the integration of Server-Sent Events in Angular

I'm currently working on incorporating Server-Sent Events (SSE) into my testing application. The server side configuration has been completed, and I am utilizing the endpoint (api/v1/sse/document). The aim here is that whenever a scan is performed, I ...

My reselect function seems to be malfunctioning - I'm not receiving any output. Can anyone help me

I'm looking to implement reselect in my code to retrieve the shopping cart based on product ids. Here's my reselect.ts file: import { createSelector } from "reselect"; import { RootState } from "../store"; export const shopp ...

Troubleshooting native web worker issues in Angular 11 - Addressing the Element Bug

After upgrading Angular to version 11, I encountered issues with utilizing web workers for heavy data processing in my project. Previously, I used webworkify-webpack (https://www.npmjs.com/package/webworkify-webpack), but it stopped working post-migration. ...

Rxjs error: The 'pipe' property is not found on the 'UnaryFunction<Observable<{}>, Observable<string | {}>>' type

Currently working on implementing ngbTypeAhead and encountering problems with RxJS version 5.5.5. The example I am referencing is from version 6 of rxjs. "rxjs": "^5.5.2" and angular "^5.0.1", "typescript": "~2.6.1", While trying to apply typeahead on f ...

Issue: The inject() function can only be executed within an injection context

Even after following the most recommended solutions online, I am still facing an issue that says Error: inject() must be called from an injection context. In addition to this error, I am also receiving multiple warnings such as: Warning: ###/src/ap ...

Parsing errors occurred when using the ngFor template: Parser identified an unexpected token at a specific column

In my Angular CLI-built application, I have a component with a model named globalModel. This model is populated with user inputs from the previous page and displayed to the user in an HTML table on the current page. Here's how it's done: <inp ...

Restricted inclusive collection utilizing embedded identifier

Attempting to segregate a discriminated union array into separate arrays of its union types has presented some challenges. I came across this particular question that provides generic discriminators. Unfortunately, the dataset I am working with doesn&apos ...