I have a Angular 8 web application where an API is called whenever the browser is closed or the browser tab is closed where my application is running. I have tried the following code
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
@HostListener('window:beforeunload', ["$event"]) unload(event) {
//calling api
}
}
The logic for the api (data in variables and functions) runs as expected, but only when i resize the browser window (inspect element) or add any breakpoint.
I also tried https://v8.angular.io/api/core/Directive#host property.
Am i adding the listener to the wrong component or the DOM object or listener is getting removed or not getting added.
The unload event can complete and window close before the call is made.
See this article to run async calls in ngOnDestroy and ensure ngOnDestroy is called on window close events (especially hot tip #1 and #2 sections).
It details how to complete a service call on the window unload event. Wesley Grimes Angular ngOnDestroy upgrades
Here is how I use it in app.component which adds a record to the database when I close the browser window:
Note - some imports may not be relevant, just copying code from my app as it is.
app.component.ts:
import { Component, OnInit, ViewChild, ElementRef, Renderer2, Input, Output, EventEmitter, HostListener, OnDestroy } from '@angular/core';
...
export class AppComponent implements OnInit, OnDestroy {
...
@HostListener('window:beforeunload')
async ngOnDestroy()
{
await this.myService.AddItem().subscribe();
}
my-service.ts:
AddItem(): Observable<any>
{
return this.http.get<any>(environment.apiURL + 'items/AddItem', httpOptions);
}
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