Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 Event emitters vs Subject

Tags:

angular

In Angular 2 what is the difference between Event Emitter and Subject for announcing an event? It seems like event emitters are less complicated to declare....Which way is preferred by Angular 2?

dataRefreshEvent = new EventEmitter();  private companyDataAnnouncedSource = new Subject(); companyDataAnnouncedSource$ = this.companyDataAnnouncedSource.asObservable(); 
like image 694
Ka Tech Avatar asked Oct 25 '16 11:10

Ka Tech


People also ask

What is the difference between event emitter and subjects?

Conclusion. Use Eventemitter when transferring data from child component to parent component. Use Subject to transfer data from one component to another component.

Is an EventEmitter and observable?

EventEmitter is used in the directives and components to emit custom events either synchronously or asynchronously. Since EventEmitter class extends RxJS subject class, this means it is observable and can be multicasted to many observers.

What are event emitters in Angular?

🎊 Event Emitters in Angular 🎊Data flows into your component via property bindings and flows out of your component through event bindings. If you want your component to notify his parent about something you can use the Output decorator with EventEmitter to create a custom event.


2 Answers

There is not much difference. EventEmitter extends Subject.

The Angular2 team stressed the fact though, that EventEmitter should not be used for anything else then @Output()s in components and directives.

The Angular team has stated that they may change the underlying implementation of EventEmitter and break user code that uses EventEmitter for something it wasn't intended for. That's the main difference.

like image 93
Günter Zöchbauer Avatar answered Sep 17 '22 20:09

Günter Zöchbauer


Also EventEmitter gets cleaned up automatically unlike custom Subjects that you need to unsubscribe to in the onDestroy lifecycle hook.

like image 28
Pro7ect Avatar answered Sep 18 '22 20:09

Pro7ect