2016-07-25 3 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)=> {...}' - レキシカルスコープを維持します「this」の – drewmoore

答えて

2

これはスコープと関係があります。あなたはonkeypressコールバックthisからthis.loginを呼び出す 時間はグローバルオブジェクトを参照するのでthis.loginはあなたのケースでは未定義である

可能な解決策

キャッシュthis

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

}; 

window.loginに等しく、コンテキストを明示的に設定する.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 
    } 

}; 
関連する問題