2016-07-25 30 views
0

我一直遇到OnInit訪問同一組件類中的函數的問題。Angular2 - OnInit訪問函數

我的基本設置如下:

import {Component, OnInit} from '@angular/core'; 
... 
export class AppComponent implements OnInit { 

login(){...} 

ngOnInit() { 

    this.login(); //1 

    document.onkeypress = function(e){ 
     if (document.body === document.activeElement) { 
      this.login(); //2 
     } 

    }; 

1將觸發頁面加載登錄功能不如預期,但2抱怨登錄不是一個函數。如何正確訪問AppComponent中的登錄功能?

+1

您需要使用箭頭功能 - 'document.onkeypress =(E)=> {...}' - 保存詞法範圍'這個' – drewmoore

回答

2

這與範圍界定有關。 你從onkeypress回調this調用this.login的時間指的是全局對象這樣this.login等於window.login而你的情況是不確定的

可能的解決方案

緩存this

var _this = this; 
document.onkeypress = function(e){ 
    if (document.body === document.activeElement) { 
     _this.login(); //2 
    } 

}; 

明確地設置上下文與.bind

document.onkeypress = function(e){ 
    if (document.body === document.activeElement) { 
     this.login(); //2 
    } 

}.bind(this); 

使用ES6箭頭功能()=>{}

document.onkeypress = (e) => { 
    if (document.body === document.activeElement) { 
     this.login(); //2 
    } 

};