Pablo Pablo - 2 years ago 711
Javascript Question

Subscribe to EventEmitter in Angular2 not working

I'm learning Angular 2. I'm trying to send data from a component to other on the click of the first one.

Both components are siblings.

This is my code so far:

First Component:

selector: 'jsonTextInput',
templateUrl: '../templates/jsonTextInput.html',
directives: [Card, CardTitle, CardDescription, Icon],
providers: [JsonChangeService]

export class JsonTextInput {
json: string = '';

constructor (private jsonChangeService: JsonChangeService) {
this.jsonChangeService = jsonChangeService

process () {

This is the service:

import {Injectable, EventEmitter} from '@angular/core';

export default class JsonChangeService {
public jsonObject: Object;

stateChange: EventEmitter<any> = new EventEmitter<any>();

constructor (){
this.jsonObject = {};

jsonChange (obj) {
console.log('sending', obj)
this.jsonObject = obj

The call from the first component to the service is working, since the
is being printed.

This is the second Component

selector: 'jsonRendered',
templateUrl: '../templates/jsonrendered.html',
directives: [Card, CardTitle],
providers: [JsonChangeService]

export class JsonRendered {
private jsonObject: Object

constructor (private jsonChangeService: JsonChangeService) {
this.jsonChangeService = jsonChangeService
this.jsonObject = jsonChangeService.jsonObject
this.jsonChangeService.stateChange.subscribe(json => { this.jsonObject = json; console.log('Change made!') })

ngOnInit () {

ngOnChanges () {

renderJson () {

The function inside the subscribe to stateChange never runs. What am I missing?


This is the content of my

_isAsync: true
_isScalar: false
destination: undefined
dispatching: false
hasCompleted: false
hasErrored: false
isStopped: false
isUnsubscribed: false
observers: Array[0]

Answer Source

You have two different instances of JsonChangeService. That's why you don't receive message between components. You need to have one instance service, i.e. on parent component or on top level like this:

bootstrap(AppComponent, [JsonChangeService])
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download