订阅Angular2中的EventEmitter不起作用 [英] Subscribe to EventEmitter in Angular2 not working
问题描述
我正在学习Angular 2.我试图通过点击第一个组件将数据从组件发送到其他组件。
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:
@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.
@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中的函数永远不会运行。我缺少什么?
The function inside the subscribe to stateChange never runs. What am I missing?
这是我的 stateChange <的内容/ code> EventEmitter:
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
推荐答案
你有两个不同的<$ c $实例C> JsonChangeService 。这就是为什么你不在组件之间接收消息。你需要有一个实例服务,即在父组件或顶层,如下所示:
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])
这篇关于订阅Angular2中的EventEmitter不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!