Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

enter image description here

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();
    }
}
like image 830
Friso Avatar asked Oct 20 '17 11:10

Friso


1 Answers

Try like this :

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

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

PostCall() {
    console.log('PostCall');
}
like image 150
Chandru Avatar answered Sep 30 '22 17:09

Chandru