3

My problem is that when i call a function who listen to the event onBeforeUnload(), i want to post a data with a httpClient request. The problem is that my request is not sent. Here the code

  @HostListener('window:beforeunload', ['$event'])
  onBeforeUnload(): void {
     this._httpClient.post(`${localhost:8080/apiRest}`, infoIWantToSent).subscribe();
  }

I don't know if this is the good way to follow. Thank you in advance for your answer.

Thales Minussi
  • 6,965
  • 1
  • 30
  • 48
scavengers
  • 221
  • 2
  • 9

2 Answers2

1

Why don't you use ngOnDestroy?

export class NewComponent implements OnDestroy{
    ngOnDestroy() {
            this._httpClient.post(${localhost:8080/apiRest}, infoIWantToSent).subscribe();
    }
}
Dulanjaya Tennekoon
  • 2,408
  • 1
  • 18
  • 31
  • Did this answer help? @scavengers – Dulanjaya Tennekoon Mar 14 '19 at 10:29
  • I can't see how this might help. The browser window is about to close. Anything async will be destroyed before it completes, probably even before anything is sent. In 2018 (if you don't need to support Internet Explorer), [`navigator.sendBeacon`](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon) is the way forward here. – spender Mar 14 '19 at 10:42
1

Thank you for your answer. the OnDestroy does'nt work in my case (never call). I find a solution by using :

@HostListener('window:beforeunload', ['$event']) onBeforeUnload(): void { const xhr = new XMLHttpRequest(); xhr.open('POST',${localhost:8080/apiRest, false); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.setRequestHeader('Authorization', 'Bearer ' + token); return xhr.send(JSON.stringify(infoIWantToSent)); } It's seems work. the token is the connexion token of my application.

scavengers
  • 221
  • 2
  • 9
  • Be aware that synchronous `XMLHttpRequest` is being phased out. There's a deprecation warning [here](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests#Synchronous_request) This solution could stop working at any time. – spender Mar 14 '19 at 16:55
  • How do we make a synchronous request without XMLHttpRequest ? – scavengers Mar 19 '19 at 15:37
  • You don't. Blocking in JavaScript a bad idea, which is why this is being phased out in the first place. The way to solve this, as said before, is using `navigator.sendBeacon`. Here's [a good write-up](https://golb.hplar.ch/2018/09/beacon-api.html) on the motivation behind `sendBeacon` (it's directly related to the problem that you are currently trying to solve). It seems like a no-brainer to me, unless you need to support Internet Explorer, in which case, use [a polyfill](https://github.com/miguelmota/Navigator.sendBeacon) – spender Mar 19 '19 at 15:51