订阅Angular2中的EventEmitter不起作用

时间:2016-05-28 15:17:04

标签: javascript angular eventemitter

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

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

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

第一部分:

@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

1 个答案:

答案 0 :(得分:3)

您有JsonChangeService的两个不同实例。这就是为什么你不在组件之间接收消息的原因。您需要有一个实例服务,即在父组件上或顶层上,如下所示:

bootstrap(AppComponent, [JsonChangeService])