【问题标题】:Subscribe to EventEmitter in Angular2 not working在 Angular2 中订阅 EventEmitter 不起作用
【发布时间】:2016-09-26 19:26:08
【问题描述】:

我正在学习 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 中的函数永远不会运行。我错过了什么?

编辑

这是我stateChangeEventEmitter的内容:

_isAsync: true
_isScalar: false
destination: undefined
dispatching: false
hasCompleted: false
hasErrored: false
isStopped: false
isUnsubscribed: false
observers: Array[0]
source:undefined

【问题讨论】:

  • this.stateChange.next 的调用真的会发出事件吗?
  • 如何检查?
  • 你能不能不直接打电话this.stateChange.emit
  • 我已将 next 更改为 emit 它仍然无法正常工作。我已通过更改更新了我的问题
  • 我还添加了stateChange内容的内容

标签: javascript angular eventemitter


【解决方案1】:

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

bootstrap(AppComponent, [JsonChangeService])

【讨论】:

  • 我的 main.ts 上有那个导入 AppComponent。但还是不行
  • Angular2 文档中的建议是将它放在AppComponent 上,而不是放在引导程序中,除非绝对必要。请参阅“配置注射器”here
  • 您是否从每个组件中删除提供程序?
  • @Pablo 从任何“子组件”的providers 部分删除服务。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-27
  • 2021-06-05
  • 2020-09-29
  • 2020-03-24
相关资源
最近更新 更多