2016-07-25 31 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 
    } 

};