Onkel Toob
Onkel Toob

Reputation: 2212

Angular: Events and "subscribe is not a function" error

I have just started diving into some basic Angular 4 and am stuck listening to an emitted event. Here's a pretty minimal example that reproduces the problem (at least on my end):

DateSenderComponent is "broadcasting" the current date which is then to be processed by its parent AppComponent (see below):

import { Component, Output } from '@angular/core';
import { EventEmitter } from "events";

@Component({
  selector: 'app-date-sender',
  template: '<button (click)="sendDate()">Send</button>'
})

export class DateSenderComponent {
  @Output() dateSent = new EventEmitter();

  sendDate(){
    var dt = new Date();
    console.log(dt);
    this.dateSent.emit(dt.toString());
  }
}

AppComponent is supposed to listen to the broadcasted date event:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: '<app-date-sender (dateSent)="dateReceived($event)"></app-date-sender>'
})

export class AppComponent {
  dateReceived(value){
    console.log('Result: ', value);
  }
}

From various beginners tutorials I figured this is the way to listen to events. However, instead of printing out the received date value, when loading the page I get the following error:

AppComponent.html:1 ERROR TypeError: instance[output.propName].subscribe is not a function

at createDirectiveInstance (core.es5.js:10727)

at createViewNodes (core.es5.js:12086)

at callViewAction (core.es5.js:12530)

at execComponentViewsAction (core.es5.js:12439)

at createViewNodes (core.es5.js:12113)

at createRootView (core.es5.js:11991)

at callWithDebugContext (core.es5.js:13206)

at Object.debugCreateRootView [as createRootView] (core.es5.js:12666)

at ComponentFactory_.create (core.es5.js:9912)

at ComponentFactoryBoundToModule.create (core.es5.js:3448)

Unfortunately, I wasn't able to find any information about what this actually means and I also couldn't figure it out on my own.

One thing that seems to be a hint: When I change the AppComponent template to listen to some event that doesn't get emitted anywhere (for example <app-date-sender (someStringSent)="dateReceived($event)"></app-date-sender>) then the error disappears. So there seems to be a connection between the actual output event and the template listening to it and it seems to be the cause of the problem.

Can anyone point me in the right direction?

Upvotes: 44

Views: 15132

Answers (2)

gpanagopoulos
gpanagopoulos

Reputation: 2920

EventEmitter should come from '@angular/core'

I see in your code it comes from 'events'.

Are you sure it is the correct object that you are using?

Upvotes: 152

Carolina Faedo
Carolina Faedo

Reputation: 875

The problem is here:

import { EventEmitter } from "events";

You have to import EventEmitter from@angular/core like this:

import { EventEmitter } from "@angular/core";

Upvotes: 28

Related Questions