【问题标题】:throws ERROR TypeError: Cannot read property 'emit' of undefined抛出 ERROR TypeError: Cannot read property 'emit' of undefined
【发布时间】:2017-12-29 12:58:32
【问题描述】:

MyComponent 中,我试图从事件处理程序发出另一个事件。 (父组件将使用这个新事件来执行一些操作)。我创建了一个事件发射器作为MyComponent 的成员,但事件处理程序方法无法访问事件发射器。它抛出ERROR TypeError: Cannot read property 'emit' of undefined。我在 StackOverflow 上找到了一些相关的问题,但由于是 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 中放置一个开关盒,并使用不同的发射器——每种类型一个。

【问题讨论】:

    标签: angular typescript event-handling youtube-api emit


    【解决方案1】:

    无法读取未定义的属性“发射”

    通常由错误的this引起。添加箭头 lambda 语法=&gt;

    修复

      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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 这为我解决了这个问题...虽然我的 ViewChild 没有未命名...我想知道是否存在加载时间问题,所以输出应该总是在 @ViewChild 之前?
      猜你喜欢
      • 2020-11-07
      • 2013-04-22
      • 1970-01-01
      • 1970-01-01
      • 2021-06-25
      • 2017-09-23
      • 2017-04-24
      • 2023-03-15
      • 1970-01-01
      相关资源
      最近更新 更多