检测浏览器或选项卡关闭-Angular

时间:2020-02-09 19:02:32

标签: javascript angular angular-material dom-events

我有一个Angular 8 Web应用程序,只要在我的应用程序运行时关闭浏览器或关闭浏览器选项卡,就会调用API。我尝试了以下代码

with open("File_name.txt", "r") as file:
       for line in file:
              #Do something with the line in the file

api的逻辑(变量和函数中的数据)按预期运行,但仅当我调整浏览器窗口(检查元素)的大小或添加任何断点时才运行。 我还尝试了https://v8.angular.io/api/core/Directive#host属性。
我是将侦听器添加到错误的组件,还是将DOM对象删除或未添加侦听器。

1 个答案:

答案 0 :(得分:0)

在调用之前,卸载事件可以完成并关闭窗口。

请参阅本文以在ngOnDestroy中运行异步调用,并确保在窗口关闭事件(尤其是热技巧#1和#2部分)上调用ngOnDestroy。

它详细说明了如何在窗口卸载事件上完成服务调用。 Wesley Grimes Angular ngOnDestroy upgrades

这是我在app.component中使用它的方式,当我关闭浏览器窗口时,它会向数据库添加一条记录:

注意-某些导入可能无关紧要,只是直接从我的应用中复制代码。

app.component.ts:

import { Component, OnInit, ViewChild, ElementRef, Renderer2, Input, Output, EventEmitter, HostListener, OnDestroy  } from '@angular/core';

...

export class AppComponent implements OnInit, OnDestroy {

...

 @HostListener('window:beforeunload')
  async ngOnDestroy()
  {
    await this.myService.AddItem().subscribe();
  }

my-service.ts:

 AddItem(): Observable<any>
 {
  return this.http.get<any>(environment.apiURL + 'items/AddItem', httpOptions);
 }