Pablo Pablo - 6 months ago 223
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:



@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.jsonChangeService.jsonChange(this.json)
}
}


This is the service:



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

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
this.stateChange.emit(this.jsonObject)
}
}


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

This is the second Component



@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 () {
console.log(1)
}

ngOnChanges () {
console.log(2)
}

renderJson () {
console.log(3)
}
}


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

EDIT



This is the content of my
stateChange
EventEmitter:

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

Answer

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])
Comments