更新至2.0稳定版:EventEmitter 现在仅用于组件通信。这是对Subjects 和ReplaySubjects 更好的使用。我已将示例更新为 2.0 代码。
UPDATED TO BETA 1: You no longer need to call .toRx() on the emitter so I'm updating the code to match and added an example to unSubscribe.
So right now (Alpha 45) The eventEmitter has that toRx() method which returns a RxJS SUBJECT
You can google a bit what that is and what you can do with it but it's what you are actually messing with. When you call toRx() it just returns the internal subject from the eventEmitter so you can do that in your service constructor.
然后我将你想要进行广播的功能添加到事件服务中
class EventService {
//could be regular Subject but I like how ReplaySubject will send the last item when a new subscriber joins
emitter: ReplaySubject<any> = new ReplaySubject(1);
constructor() {
}
doSomething(data){
this.emitter.next(data);
}
}
然后在您的组件中订阅发射器
class ParentCmp {
myData: any;
constructor(private evt: EventService) {
//rx emitter
this.evt.emitter.subscribe((data) => {
this.myData = data;
console.log("I'm the parent cmp and I got this data", data));
}
}
}
这是一个带有内置 unsubscribe(dispose) 的扩展类
export class ParentCmp implements OnDestroy {
myData: any;
subscription: any;
constructor(evt: EventService) {
//rx emitter
this.subscription = evt.emitter.subscribe((data) => {
this.myData = data;
console.log("I'm the parent cmp and I got this data", data));
}
}
ngOnDestroy() {
this.subscription.dispose();
}
}
我对你的最后一个问题有点困惑,但想到“接收消息”这个词。你必须的倾听这就是 subscribe 方法所做的并且是必需的。
很酷的是,现在您可以在任何地方(甚至在其他服务中)调用可观察的,并且 IMO 是组件之间通信的最佳方式。他们不需要知道自己在树中的位置,也不需要关心其他组件是否存在或正在监听。
我用我的工作方式分叉了你的 PlunkerHERE http://plnkr.co/edit/DAsLAT?p=preview
(仍在Alpha45上)
RxJs 来源和主题信息 https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/subjects/subject.md
Angular2 源代码和有关 eventEmitter 内主题的信息 https://github.com/angular/angular/blob/2.0.0-alpha.45/modules/angular2/src/core/facade/async.ts#L116