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

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -

java - Digest auth with Spring Security using javaconfig -