如何使用 @HostListener('window:beforeunload') 调用方法?

编程入门 行业动态 更新时间:2024-10-21 20:27:57
本文介绍了如何使用 @HostListener('window:beforeunload') 调用方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我正在尝试调用我在卸载组件之前自己创建的 post 方法,但它不起作用.

I am trying to call a post method I made myself before my component is unloaded, but it doesn't work.

我在@HostListener 上设置了一个断点,当我打开不同的组件时它不会在那里中断.

I put a breakpoint on @HostListener and it doesn't break there when I open a different component.

我正在使用 Chrome 进行调试,并为卸载和卸载前打开了事件侦听器断点,当我打开不同的组件时会中断.

I'm using Chrome to debug and I turned on Event Listener Breakpoints for unload and beforeunload, which do break when I open a different component.

我的代码中是否遗漏了什么?

Am I missing something in my code?

import { Component, OnInit, HostListener } from '@angular/core';

Component({
    templateUrl: 'new-component.html'    
})

export class NewComponent implements OnInit {
    @HostListener('window:beforeunload') onBeforeUnload() {
            PostCall();
    }
}

推荐答案

window:beforeunload 是在实际卸载页面之前触发的浏览器事件.

window:beforeunload is a browser event which is triggered right before actually unloading the page.

当您导航到另一个组件时,实际上并不是在卸载页面.

When you navigate to another component, you are not actually unloading the page.

你需要做的是使用 ngOnDestroy ,它会在组件被销毁时被调用.实现如下接口:

What you need to do is use ngOnDestroy which will be called when component is being destroyed. Implements the following interface:

https://angular.io/api/core/OnDestroy

示例:

export class NewComponent implements OnDestroy{
    ngOnDestroy() {
            PostCall();
    }
}

这篇关于如何使用 @HostListener('window:beforeunload') 调用方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-22 12:32:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1023574.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   方法   HostListener   window   beforeunload

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!