本文介绍了如何使用@HostListener('window:beforeunload')调用方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图调用在卸载组件之前创建的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进行调试,并且我打开了事件监听器断点进行卸载和beforeunload,当我打开其他组件时,断点确实会中断.

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')调用方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 09:36