簡體   English   中英

Angular2-OnInit訪問功能

[英]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.loginonkeypress回調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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM