Subscribe to EventEmitter in Angular2 not working

夙愿已清 提交于 2019-12-21 05:39:10

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/37500698/subscribe-to-eventemitter-in-angular2-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!