gpt4 book ai didi

angular - EventEmitter 的正确用法是什么?

转载 作者:太空狗 更新时间:2023-10-29 16:44:15 24 4
gpt4 key购买 nike

我读过类似 Access EventEmitter Service inside of CustomHttp 的问题用户在他的服务中使用 EventEmitter,但在此 comment 中建议他使用不使用它,而是直接在他的服务中使用 Observables。

我也看过这个 question解决方案建议将 EventEmitter 传递给 child 并订阅它。

我的问题是:我应该还是不应该手动订阅 EventEmitter?我应该如何使用它?

最佳答案

长话短说:

不,不要手动订阅它们,不要在服务中使用它们。如文档中所示使用它们仅在组件中发出事件。不要打败 Angular 的抽象。

答案:

不,您不应该手动订阅它。

EventEmitter是一个 angular2 抽象,它的唯一目的是在组件中发出事件。引用 comment来自 Rob Wormald

[...] EventEmitter is really an Angular abstraction, and should be used pretty much only for emitting custom Events in components. Otherwise, just use Rx as if it was any other library.

这在 EventEmitter 的文档中说得很清楚。

Use by directives and components to emit custom Events.

使用它有什么问题?

Angular2 永远不会向我们保证 EventEmitter 将继续作为一个 Observable。所以这意味着如果我们的代码发生变化就重构它。我们必须访问的唯一 API 是它的 emit() 方法。我们永远不应该手动订阅 EventEmitter。

上述所有内容在 Ward Bell 的 comment 中更加清晰(建议阅读文章,并在评论中添加 answer)。引用引用

Do NOT count on EventEmitter continuing to be an Observable!

Do NOT count on those Observable operators being there in the future!

These will be deprecated soon and probably removed before release.

Use EventEmitter only for event binding between a child and parent component. Do not subscribe to it. Do not call any of those methods. Only call eve.emit()

他的评论与很久以前 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>
`
})
class Parent {
getNotification(evt) {
// Do something with the notification (evt) sent by the child!
}
}

怎么不用呢?

class MyService {
@Output() myServiceEvent : EventEmitter<any> = new EventEmitter();
}

停在那里...你已经错了...

希望这两个简单的示例能够阐明 EventEmitter 的正确用法。

关于angular - EventEmitter 的正确用法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36076700/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com