简体   繁体   English

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

[英]Detect Browser or tab close - Angular

I have a Angular 8 web application where an API is called whenever the browser is closed or the browser tab is closed where my application is running.我有一个 Angular 8 Web 应用程序,只要关闭浏览器或关闭我的应用程序运行的浏览器选项卡,就会调用 API。 I have tried the following code我试过下面的代码

    @Component({
     selector: 'app-root',
     templateUrl: './app.component.html',
     styleUrls: ['./app.component.scss']
    })
    export class AppComponent {
     @HostListener('window:beforeunload', ["$event"]) unload(event) {
        //calling api
     }
    }

The logic for the api (data in variables and functions) runs as expected, but only when i resize the browser window (inspect element) or add any breakpoint. api 的逻辑(变量和函数中的数据)按预期运行,但仅当我调整浏览器窗口大小(检查元素)或添加任何断点时。 I also tried https://v8.angular.io/api/core/Directive#host property.我也试过https://v8.angular.io/api/core/Directive#host属性。
Am i adding the listener to the wrong component or the DOM object or listener is getting removed or not getting added.我是否将侦听器添加到错误的组件或 DOM 对象或侦听器被删除或未添加。

The unload event can complete and window close before the call is made.卸载事件可以在调用之前完成并关闭窗口。

See this article to run async calls in ngOnDestroy and ensure ngOnDestroy is called on window close events (especially hot tip #1 and #2 sections).请参阅本文以在 ngOnDestroy 中运行异步调用,并确保在窗口关闭事件上调用 ngOnDestroy(尤其是热点提示 #1 和 #2 部分)。

It details how to complete a service call on the window unload event.它详细说明了如何在窗口卸载事件上完成服务调用。 Wesley Grimes Angular ngOnDestroy upgrades Wesley Grimes Angular ngOnDestroy 升级

Here is how I use it in app.component which adds a record to the database when I close the browser window:这是我在 app.component 中使用它的方法,当我关闭浏览器窗口时,它会向数据库添加一条记录:

Note - some imports may not be relevant, just copying code from my app as it is.注意 - 一些导入可能不相关,只是从我的应用程序中复制代码。

app.component.ts: 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:我的服务.ts:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM