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

Sonu Mishra picture Sonu Mishra · Jul 24, 2017 · Viewed 33.2k times · Source

In MyComponent, I am trying to emit another event from an event handler. (This new event will be used by the parent component to take a few actions). I created an event emitter as a member of MyComponent, but the event handler method is not able to access the event emitter. It throws ERROR TypeError: Cannot read property 'emit' of undefined. I found some related questions on StackOverflow, but could not comprehend much due to being new to 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`
  }    
}

Could someone help me out? Please note that I have to emit events only from onStateChangeEvent, because later I will have different types of event emitters for different types of events. So I will put a switch-case inside onStateChangeEvent and will use different emitters - one for each type.

Answer

basarat picture basarat · Jul 24, 2017

Cannot read property 'emit' of undefined

Commonly caused by wrong this. Add the arrow lambda syntax =>

Fix

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

More

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