2017-10-20 205 views
0

我正試圖調用我自己在卸載組件之前調用的post方法,但它不起作用。如何使用@HostListener('window:beforeunload')來調用方法?

我在@HostListener上放置了一個斷點,當我打開一個不同的組件時,它不會在那裏出現斷點。

我正在使用Chrome進行調試,並且我打開了用於卸載和beforeunload的事件偵聽器斷點,當打開不同的組件時會斷開事件偵聽器斷點。

enter image description here

我失去了我的代碼的東西嗎?

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是是正確的其實之前卸載頁面引發了瀏覽器的事件。

當您導航到另一個組件時,實際上並沒有卸載該頁面。

你需要做的是使用ngOnDestroy當組件被銷燬時將被調用。實現以下接口:

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

實施例:

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

嘗試這樣的:

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

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

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