![](/img/trans.png)
[英]Angular2 OnInit data loading too slow causing undefined TypeError
[英]Angular2 - OnInit accessing functions
我一直遇到與同一組件類中的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中的登錄功能?
這與范圍界定有關。 您呼叫的時間this.login
從onkeypress
回調this
指的是全局對象這樣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
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.