Angular 8 beforeunload event event not work on close tab

岁酱吖の 提交于 2021-02-11 13:35:34

问题


Hey i try to make http request on close tab but its not work, But if i navigate to other component its work. I try to change the function like this post Angular 2 - Execute code when closing window

But its now work for me.

My http service:

  removeCurrentEditor(reportID) {
    return this.http.request('GET', this.baseUrl + this.REPORTS_API + '/' + this.REMOVE_CURRENT_EDITOR
     + '/' + reportID, {responseType: 'json'});
  }

my component:

 // Handle close tab
  @HostListener('window:beforeunload', ['$event'])
  beforeUnloadHander(event) {
    this.reportService.removeCurrentEditor(this.reportID);
  }

Thanks !


回答1:


We had a similar issue with our application where we had to issue a http call on close of browser tab. The problem is when the browser is closed, it cancels all xhr calls. Hence there was no way to achieve this and angular does not support syncronous http calls out of the box.

Finally, we ended up using a synchronous xmlhttprequest in the onBeforeUnload event. This way, the browser waits for the call to complete before closing the browser.

XMLHttpRequest.open(method, url[, async[, user[, password]]])

The async parameter if set to false indicates a synchronous request.

Another option you could explore is something like a heartbeat client which could detect if the application is open. If not, the server could perform the logic.



来源:https://stackoverflow.com/questions/59021445/angular-8-beforeunload-event-event-not-work-on-close-tab

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!