I have a component in Angular 15 that when the window or tab is closed requires an API call to my backend. I tried to solve it like bellow, but apparently this is not a good solution, as using fetch will not guarantee that the call is successfully finished. What can I do to make sure, the window is only closed when my API call finished? (Hopefully with success but in error case it should still close the window then.)
@HostListener('window:beforeunload', ['$event'])
beforeUnloadHandler(event) {
if (this.sll_ID && this.auth.getUser().id) {
const headerDict = {
'Authorization': this.auth.getAuthToken()
}
const formData = new FormData();
formData.append('id', JSON.stringify(this.sll_ID))
formData.append('locked', JSON.stringify(0))
formData.append('locked_by', JSON.stringify(this.auth.getUser().id))
fetch(environment.apiUrl + "/api/sllorderlock/", {
method: 'POST',
headers: headerDict,
body: formData,
keepalive: true,
});
}
}
working with the beforeunload event to make an API call before the window or tab closes is a bit complicated since you can never be sure that the request will complete before the page loads.
The beforeunload event is just allows you to show a confirmation dialog, and browsers typically do not wait for asynchronous operations to be done.
A way to come up with a solution to this problem is to make synchronous API calls, but always keep in mind that synchronous requests are generally discouraged as they can freeze the UI and provide a bad experience for users.