Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't post a httpClient request when call before unload

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.

like image 365
scavengers Avatar asked Jun 25 '26 15:06

scavengers


2 Answers

Why don't you use ngOnDestroy?

export class NewComponent implements OnDestroy{
    ngOnDestroy() {
            this._httpClient.post(${localhost:8080/apiRest}, infoIWantToSent).subscribe();
    }
}
like image 80
Dulanjaya Tennekoon Avatar answered Jun 28 '26 05:06

Dulanjaya Tennekoon


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.

like image 45
scavengers Avatar answered Jun 28 '26 04:06

scavengers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!