How to unsubscribe from EventEmitter in Angular 2?

tom10271 picture tom10271 · Apr 8, 2016 · Viewed 21.7k times · Source
export declare class EventEmitter<T> extends Subject<T> {
    /**
     * Creates an instance of [EventEmitter], which depending on [isAsync],
     * delivers events synchronously or asynchronously.
     */
    constructor(isAsync?: boolean);
    emit(value: T): void;
    /**
     * @deprecated - use .emit(value) instead
     */
    next(value: any): void;
    subscribe(generatorOrNext?: any, error?: any, complete?: any): any;
}

In Official Angular 2 Typescript definition, seems it has no way to mute or unsubscribe from EventEmitter.

I got callback over time as pages use the same EventEmitter

Answer

G&#252;nter Z&#246;chbauer picture Günter Zöchbauer · Apr 8, 2016

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.