javascript - Subscribe to EventEmitter in Angular2 not working -
i'm learning angular 2. i'm trying send data component other on click of first one.
both components siblings.
this code 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 service:
import {injectable, eventemitter} '@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 first component service working, since sending
being printed.
this 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 subscribe statechange never runs. missing?
edit
this content of statechange
eventemitter:
_isasync: true _isscalar: false destination: undefined dispatching: false hascompleted: false haserrored: false isstopped: false isunsubscribed: false observers: array[0] source:undefined
you have 2 different instances of jsonchangeservice
. that's why don't receive message between components. need have 1 instance service, i.e. on parent component or on top level this:
bootstrap(appcomponent, [jsonchangeservice])
Comments
Post a Comment