我的应用程序即将关闭时如何调用API

时间:2019-05-16 06:50:20

标签: angular angular-http

我想点击一个API来设置用户的上次激活时间。 但是API并没有成功。 由于API需要花费一些时间来初始化和命中服务器,并且在命中API之前,应用程序已关闭

我在app.component.ts文件中尝试了此代码

    @HostListener('window:beforeunload', [ '$event' ])
      beforeUnloadHander(event) {
        this._apiService.setLastActive({time:new Date().getTime()/1000})
          .subscribe(data => {
          },err=> {
          })
      }

有人可以建议我何时调用API来设置用户的最后活动状态吗?

3 个答案:

答案 0 :(得分:1)

请在现有组件的component.ts文件中使用ngOnDestroy()

功能
它在Angular销毁指令/组件之前进行清理。取消订阅Observables并分离事件处理程序,以避免内存泄漏,并在Angular破坏指令/组件之前进行调用。https://angular.io/guide/lifecycle-hooks

如果尚未保存更改。试试这个stackoverflow答案 Confirmation before closing of tab/browser

答案 1 :(得分:0)

刚刚遇到了这个问题:https://stackoverflow.com/a/54920520/982517。似乎beforeunload不支持异步,因此您将不得不使用XMLHttpRequest来调用您的API。

在另一篇文章中:

window.addEventListener("beforeunload", function (event) {
  var client = new XMLHttpRequest();
  client.open("POST", "http://url/to/endsession", false); // third parameter indicates sync xhr
  client.setRequestHeader("Content-Type", "application/json");
  client.send('{userId: "42"}');
  console.log('done!!!'); // outputs when a response is received 
});

答案 2 :(得分:0)

使用javascript代码,可能对您有用。

window.onbeforeunload = e => {
    e.returnValue = 'Do you really want to leave this site?';
    return dialogText;
};