Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 992
Sonu Mishra Avatar asked Jul 24 '17 03:07

Sonu Mishra


2 Answers

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

like image 72
basarat Avatar answered Nov 13 '22 16:11

basarat


For anyone that came here to find this, if Basarats solution did not work, check to make sure that the line above the event emitter does not have any typos. I had an unnamed ViewChild above my undefined EventEmitter.

like image 40
Nick Gallimore Avatar answered Nov 13 '22 16:11

Nick Gallimore