angular2 – EventEmitter的正确使用是什么?
我读过问题,如
Access EventEmitter Service inside of CustomHttp
用户在他的服务中使用EventEmitter,但他在 comment建议 不要使用它,并直接在他的服务中使用Observable。 我也读这个 我的问题是:我应该,还是我不应该手动订阅一个EventEmitter?我应该如何使用它?
不,您不应手动订阅。
EventEmitter是一个angular2抽象,它的唯一目的是在组件中发出事件。从Rob Wormald引用一个comment
这在EventEmitter的文档中非常清楚。
使用它有什么问题? Angular2永远不会保证我们EventEmitter将继续作为一个Observable。这意味着重构我们的代码,如果它改变。唯一必须访问的API是emit()方法。我们不应该手动订阅一个EventEmitter。 上面所有的说明在这个Ward Bell的comment(推荐阅读文章,和answer的那个意见)中更清楚。报价参考
他的评论很久以前就符合Rob的评论。 那么,如何正确使用呢? 只需使用它从你的组件发出事件。看看下面的例子。 @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> `,directives : [Child] }) class Parent { getNotification(evt) { // Do something with the notification (evt) sent by the child! } } 如何不使用呢? class MyService { @Output() myServiceEvent : EventEmitter<any> = new EventEmitter(); } 停在那里…你已经错了… 希望这两个简单的例子将澄清EventEmitter的正确使用。 TL; DR答案: 不,不要手动订阅,不要在服务中使用它们。使用它们,如文档中所示仅用于在组件中发出事件。不要打败角的抽象。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |