如何将事件分配给打字稿中的变量

问题描述 投票:0回答:1

试图在变量中分配事件,但不起作用。我不知道如何分配。我进入console.log(this.myEvents)像null。如果有人知道,请帮助找到解决方案。

app.component.ts:

public myEvents:any; 
logEvent(e)
{ 
    this.myEvents=e; // Store event info
}

// Set a timer for looping through the events
gameTimer = setInterval(function() {
    // Loop through events
    if(this.myEvents)
    {
        console.log(this.myEvents);// getting null

    }
}, 100)​

app.component.html:

<button (click)="logEvent(e)">Set event</button>
typescript angular6 angular7 angular8
1个回答
0
投票

您必须在setInterval () =>中使用箭头功能,否则this指针未显示在组件上,并且您无法分配给this.myEvents

我未经测试就修复了您的组件:

class Game implements OnInit, OnDestroy {
    public myEvents: any; 

    private gameTimer: any = null;

    constructor() {

    }

     // Set a timer for looping through the events
    ngOnInit() {
        this.gameTimer = setInterval(() => {
            // Loop through events
            if (this.myEvents) {
                console.log(this.myEvents);// getting null

            }
        }, 100);​
    }

    ngOnDestroy() {
        if (this.gameTimer !== null) {
            clearInterval(this.gameTimer);
        }
    }

    logEvent(e: any)
    { 
        this.myEvents = e; // Store event info
    }

}

重要的部分:

this.gameTimer = setInterval(() => {
                // Loop through events
                if (this.myEvents) {
                    console.log(this.myEvents);// getting null

                }
            }, 100);​
© www.soinside.com 2019 - 2024. All rights reserved.