Ben Nadel
On User Experience (UX) Design, JavaScript, ColdFusion, Node.js, Life, and Love.
Ben Nadel at Scotch On The Rock (SOTR) 2010 (Brussels) with: Ray Camden and Alison Huselid and David Huselid
Ben Nadel at Scotch On The Rock (SOTR) 2010 (Brussels) with: Ray Camden@cfjedimaster ) , Alison Huselid , and David Huselid

EXCEPTION: TypeError: Cannot Read property 'subscribe' Of Undefined In AngularJS 2 Beta 1

By Ben Nadel on

In AngularJS 2, directives can announce / trigger output events using the EventEmitter class (ng.core.EventEmitter). Each output must get its own instance of the EventEmitter class, which means that you must instantiate the EventEmitter when you are implementing your output event stream. If you forget to "new" the EventEmitter, such as typing:

this.myEvent = ng.core.EventEmitter();

... you will get the following error:

EXCEPTION: TypeError: Cannot read property 'subscribe' of undefined.

Notice that I forgot to "new" the EventEmitter into existence. Invoking it in this way downgrades the EventEmitter() constructor into a simple "function call". The fix is easy - just add "new":

this.myEvent = new ng.core.EventEmitter();

I've tripped over this like at least 4 or 5 times already this week; so, I figured I'd just make a record of it incase anyone also runs into the error and tries to Google for the error message.



Looking For A New Job?

Ooops, there are no jobs. Post one now for only $29 and own this real estate!

100% of job board revenue is donated to Kiva. Loans that change livesFind out more »

Reader Comments

Thanks for this - Saw this error when i set up an Output without wiring it up and had no idea why the error was appearing or what it meant.

What a waste of an hour, running around trying to figure out where I was trying to call 'subscribe'. Course, this makes complete sense!! Thanks!

Ben,

I had this same error today, but I was already using "new" when instantiating the event emitter. It turns out I was doing it in the ngOnInit method instead of the constructor. I figured I would post in case someone else was having this issue, since it throws the same error message.

Thanks your sharing here. The issue is so unclear and confusing, wouldn't have been resolved until read your reminding.

@Dave,

Thank you and everyone else for posting this.. I too forgot to new up the event emitter and was stuck on this for an hour!

@Chris,

Yep - ran accross this today as well. Thanks for posting. I'm new to Angular 2 and at first I tried to instantiate it in the ngOnInit as well. Has to be a timing thing. I know @Input() values exist before the ngOnInit so I'm guessing the @Output()s need to as well.