繁体   English   中英

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

[英]Detect Browser or tab close - Angular

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

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

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

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

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

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

这是我在 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();
  }

我的服务.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