throws ERROR TypeError: Cannot read property 'emit' of undefined

throws ERROR TypeError: Cannot read property 'emit' of undefined

MyComponent 中,我试图从事件处理程序发出另一个事件。 (父组件将使用这个新事件来执行一些操作)。我创建了一个事件发射器作为 MyComponent 的成员,但事件处理程序方法无法访问事件发射器。它抛出 ERROR TypeError: Cannot read property 'emit' of undefined。我在 Whosebug 上找到了一些相关问题,但由于是 Angular2.

的新手,无法理解太多
import { Component, Input, Output, OnChanges, SimpleChanges, OnInit, EventEmitter } from '@angular/core';

import YouTubePlayer from 'youtube-player';

@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.css']
})

export class MyComponent implements OnChanges, OnInit {
  @Input()
  videoURL = '';

  player : any;

  videoId : any;

  @Output()
  myEmitter: EventEmitter<number> = new EventEmitter();

  ngOnInit(): void {
    this.player = YouTubePlayer('video-player', {
        videoId: this.videoId,
        width: "100%"
    });
    this.registerEvents();
  }

  private registerEvents() {
    this.player.on("stateChange", this.onStateChangeEvent);
  }

  private onStateChangeEvent(event: any) {
    console.log("reached here: " + event);
    this.myEmitter.emit(1); //throws `ERROR TypeError: Cannot read property 'emit' of undefined`
  }    
}

有人能帮帮我吗?请注意,我必须仅从 onStateChangeEvent 发出事件,因为稍后我将针对不同类型的事件使用不同类型的事件发射器。因此,我将在 onStateChangeEvent 内放置一个开关盒,并将使用不同的发射器 - 每种类型一个。

Cannot read property 'emit' of undefined

通常由错误this引起。添加箭头 lambda 语法 =>

修复

  private onStateChangeEvent = (event: any) => {
    console.log("reached here: " + event);
    this.myEmitter.emit(1); // now correct this
  }  

更多

https://basarat.gitbooks.io/typescript/docs/arrow-functions.html

如果 Basarats 解决方案不起作用,请检查以确保事件发射器上方的行没有任何拼写错误。我在未定义的 EventEmitter 上方有一个未命名的 ViewChild。