简体   繁体   English

Angular2-OnInit访问功能

[英]Angular2 - OnInit accessing functions

I keep running into issues with OnInit accessing functions within the same component class. 我一直遇到与同一组件类中的OnInit访问函数有关的问题。

My basic setup is as follows: 我的基本设置如下:

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 will fire the login function on page load as expected, but 2 complains login isn't a function. 1将按预期在页面加载时触发登录功能,但2抱怨登录不是功能。 How do I appropriately access the login function within AppComponent? 如何正确访问AppComponent中的登录功能?

This has to do with scoping. 这与范围界定有关。 The time you call this.login from the onkeypress callback this refers to the global object so this.login is equal to window.login which in your case is undefined 您呼叫的时间this.loginonkeypress回调this指的是全局对象这样this.login等于window.login而你的情况是不确定的

Possible solutions 可能的解决方案

Cache this 缓存this

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

};

Explicitly set context with .bind .bind显式设置上下文

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

}.bind(this);

Use ES6 arrow functions ()=>{} 使用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