How can I use @HostListener('window:beforeunload') to call a method?

非 Y 不嫁゛ 提交于 2019-11-30 13:29:07

问题


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

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

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();
    }
}

回答1:


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.

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

Example:

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



回答2:


Try like this :

@HostListener('window:unload', ['$event'])
unloadHandler(event) {
    this.PostCall();
}

@HostListener('window:beforeunload', ['$event'])
beforeUnloadHander(event) {
    return false;
}

PostCall() {
    console.log('PostCall');
}



回答3:


Simply use the window:beforeunload event with HostListener, the listener will be destroyed with the component.

Return false will make an alert :)

@HostListener('window:beforeunload')
  onBeforeUnload() {
    return false;
}


来源:https://stackoverflow.com/questions/46848628/how-can-i-use-hostlistenerwindowbeforeunload-to-call-a-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!