I'm attempting to trigger a POST HTTP request right before the browser closes.
Essentially, I want to detect when the user closes the page and send a call, but the request isn't completing before shutdown.
It seems like a traditional HTTP request won't work due to the need to subscribe to it.
I experimented with a solution from this source: Angular 2 - Execute code when closing window
However, this approach is not suitable for my requirements as I am working with more than just a simple GET request. Here's what I have attempted so far.
component.ts
@HostListener('window:beforeunload', ['$event'])
beforeunloadHandler($event) {
this.eventsService.sendEvent(this.form.value).subscribe(() => {
console.log("Request sent successfully");
});
}
service.ts
sendEvent(userData): Observable<any> {
return this.http.post<any>(this.url, userData,
{
headers: new HttpHeaders({
"Content-Type": "application/json"
})
})
}
Is it possible to implement XMLHttpRequest() as suggested in the above solution? What are some alternative options to achieve this functionality?
Any assistance will be highly appreciated.