问题描述
我正在尝试调用我在卸载组件之前自己创建的 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') 调用方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!