订阅Angular2中的EventEmitter无法正常工作

Pab*_*blo 3 javascript eventemitter angular

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

这两个组成部分都是兄弟姐妹。

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

第一部分:

@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)
  }
}
Run Code Online (Sandbox Code Playgroud)

这是服务:

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)
  }
}
Run Code Online (Sandbox Code Playgroud)

由于第一个组件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)
  }
}
Run Code Online (Sandbox Code Playgroud)

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

编辑

这是我的stateChangeEventEmitter 的内容:

_isAsync: true
_isScalar: false
destination: undefined
dispatching: false
hasCompleted: false
hasErrored: false
isStopped: false
isUnsubscribed: false
observers: Array[0]
source:undefined
Run Code Online (Sandbox Code Playgroud)

yur*_*zui 5

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

bootstrap(AppComponent, [JsonChangeService])
Run Code Online (Sandbox Code Playgroud)

  • Angular2文档中的建议是将其放在AppComponent上,而不是放在引导程序中,除非绝对必要。请参阅“配置注射器” [此处](https://angular.io/docs/ts/latest/guide/dependency-injection.html) (2认同)
  • @Pablo从任何“子组件”的“提供商”部分删除该服务。 (2认同)