2017-08-24 63 views
0

我有一個Angular2應用程序,並且我想在用戶關閉瀏覽器窗口時執行一些邏輯。我在使用之前,請先卸載瀏覽器窗口的事件。我已將以下代碼放入TypeScript類構造函數中:如何從匿名函數訪問全局打印字體變量

export class MyAngularComponent implements OnInit, OnDestroy { 

    callServer() 
    { 
    //Logic to call the server 
    } 

    constructor(private updateServiceFactory: UpdateService) { 

    window.onbeforeunload = function(e){ 
     this.callServer(); //this does not work    
    } 
    } 
} 

我正在獲取this.callServer()行中的編譯錯誤。錯誤顯示「Property'callServer'在類型'Window'上不存在」。我明白,在匿名函數的上下文中的「this」是指Window對象。

問:如何從匿名函數內部調用callServer()方法?

回答

2

使用箭頭功能而不是簡單的功能。 Arrow函數從聲明的上下文中捕獲它。

export class MyAngularComponent implements OnInit, OnDestroy { 

    callServer() 
    { 
    //Logic to call the server 
    } 

    constructor(private updateServiceFactory: UpdateService) { 

    window.onbeforeunload = (e) => { 
     this.callServer(); //this now refers to MyAngularComponent    
    } 
    } 
} 
+0

任何關心評論爲什麼他們投票?想知道問題是什麼,也許我可以修復它:) –

+0

我的回答和問題也是downvoted,所以我懷疑有人剛剛經歷了一些原因(盲目downvoted一切出於某種原因)(其他答案尚未公佈)。 –

+1

@Diopside有一點,如果角度提供了一種方式來監聽主機事件,最好使用它:) –

2

您可以使用bind改變功能的this到正確的上下文。

window.onbeforeunload = function(e){ 
    this.callServer(); 
}.bind(this) 
+0

這和接受的答案一樣好,但泰坦是第一個。 – myroslav

4

嘗試在組件中使用HostListener,而不是在構造函數中。

@HostListener('window:beforeunload', ['$event']) 
doSomething($event) { 
    // your code here // 
} 

構造通常不是做多的東西直接關係到傳遞到構造函數的參數以外的任何其他的好地方。

+0

這個效果和接受的答案一樣好,但泰坦是第一個。 – myroslav