How to unsubscribe from EventEmitter in Angular 2?
As mentioned by Günter Zöchbauer you can unsubscribe from EventEmitter as following:
someOutput: EventEmitter = new EventEmitter();
...
this.subscription = someOutput.subscribe(...);
...
this.subscription.unsubscribe();
Since Angular says you should not use EventEmitter for things other than @Output (taken from this post):
Quoting a comment from 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.
This is stated really clear in EventEmitter's documentation.
Use by directives and components to emit custom Events.
Instead you should be using the Rxjs Subject. EventEmitter extends the Rxjs Subject which means you can pretty much use it in the same way. Although you have to use the "subject.next()" function instead of "eventEmitter.emit()", subscribe and unsubscribe work the same.
someOutput: EventEmitter = new Subject();
...
this.subscription = someOutput.subscribe(...);
...
this.subscription.unsubscribe();
Because EventEmitters should only be used to emit events from components, and hence they should not be subscribed to, there is no need for Angular to provide a means to unsubscribe.
If you are not using an output property in a component, use an Observable or a Subject instead of an EventEmitter.
Maybe they should change the name to OutputPropertyEmitter.
EventEmitter extends Subject. When you subscribe to a subject you get a Subscription
which you can later use to unsubscribe.
someOutput:EventEmitter = new EventEmitter();
...
this.subscription = someOutput.subscribe(...);
...
this.subscription.unsubscribe();
Hint
Don't use EventEmitter
for anything else but @Output()
s. Angular doesn't guarantee that EventEmitter
will keep extending Subject
or even work similar to a Subject
in the future.