throws ERROR TypeError: Cannot read property 'emit' of undefined
Asked Answered
D

2

19

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.

Danella answered 24/7, 2017 at 3:23 Comment(1)
developer.mozilla.org/en-US/docs/Web/API/…Gismo
S
46

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

Stokowski answered 24/7, 2017 at 3:28 Comment(0)
F
4

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.

Furbish answered 30/8, 2019 at 13:54 Comment(2)
This fixed it for me...although my ViewChild is not unnamed...I'm wondering if there is a load timing issue so Output should always precede @ViewChild?Variegated
@Variegated OMG thank you so much - moving the @ViewChild before @Output fixed it!!!Tadtada

© 2022 - 2024 — McMap. All rights reserved.