我正在学习Angular2。我试图通过单击第一个组件将数据从组件发送到其他组件。

这两个组成部分都是 sibling 。

到目前为止,这是我的代码:

第一部分:

@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)
  }
}

这是服务:
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)
  }
}

从第一个组件到服务的调用正在工作,因为正在打印sending

这是第二个组成部分
@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)
  }
}

订阅stateChange的函数永远不会运行。我想念什么?

编辑

这是我的stateChange EventEmitter的内容:
_isAsync: true
_isScalar: false
destination: undefined
dispatching: false
hasCompleted: false
hasErrored: false
isStopped: false
isUnsubscribed: false
observers: Array[0]
source:undefined

最佳答案

您有JsonChangeService的两个不同实例。因此,您不会在组件之间收到消息。您需要具有一个实例服务,即在父组件或顶级上像这样:

bootstrap(AppComponent, [JsonChangeService])

09-25 20:27