TL;DR:
不,不要手动订阅它们,不要在服务中使用它们。如文档中所示使用它们仅在组件中发出事件。不要破坏 Angular 的抽象。
答案:
不,您不应该手动订阅它。
EventEmitter 是一个 angular2 抽象,其唯一目的是在组件中发出事件。引用 Rob Wormald 的comment
[...] EventEmitter 实际上是一个 Angular 抽象,应该仅用于在组件中发出自定义事件。否则,只需像使用任何其他库一样使用 Rx。
这在 EventEmitter 的文档中说得很清楚。
使用 by 指令和组件来发出自定义事件。
使用它有什么问题?
Angular2 永远不会保证 EventEmitter 将继续成为 Observable。所以这意味着如果我们的代码发生变化,就要重构它。我们必须访问的唯一 API 是它的 emit() 方法。我们永远不应该手动订阅 EventEmitter。
上述所有内容在 Ward Bell 的 comment 中更加清晰(建议阅读这篇文章,answer 对该评论)。引用参考
不要指望 EventEmitter 继续成为 Observable!
不要指望那些 Observable 运算符将来会出现!
这些将很快被弃用,并可能在发布前被删除。
仅将 EventEmitter 用于子组件和父组件之间的事件绑定。不要订阅它。不要调用任何这些方法。只打电话eve.emit()
他的评论与罗布很久以前的评论一致。
那么,如何正确使用呢?
只需使用它从您的组件中发出事件。看看下面的例子。
@Component({
selector : 'child',
template : `
<button (click)="sendNotification()">Notify my parent!</button>
`
})
class Child {
@Output() notifyParent: EventEmitter<any> = new EventEmitter();
sendNotification() {
this.notifyParent.emit('Some value to send to the parent');
}
}
@Component({
selector : 'parent',
template : `
<child (notifyParent)="getNotification($event)"></child>
`
})
class Parent {
getNotification(evt) {
// Do something with the notification (evt) sent by the child!
}
}
怎么不用呢?
class MyService {
@Output() myServiceEvent : EventEmitter<any> = new EventEmitter();
}
停在那里……你已经错了……
希望这两个简单的例子能够阐明 EventEmitter 的正确用法。