【发布时间】: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