Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unsubscribe from EventEmitter in Angular 2?

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

like image 696
tom10271 Avatar asked Apr 08 '16 08:04

tom10271


People also ask

Do I need to unsubscribe from EventEmitter?

Since You are not using child to parent component iteration for fetching data from API there is no need to unsubscribe.

Can we subscribe to EventEmitter?

subscribe() is an EventEmitter method that registers handlers for events emitted by this instance. subscribe() have three optional parameters which can be used to pass values, errors, or completion notification in EventEmitter . The next parameter is a custom handler for emitted events.

Do we need to unsubscribe subject?

You always have to unsubscribe from: Any Observable or Subject you created manually.

How do you pass two parameters in EventEmitter?

For passing the parameters, we will wrap all the parameters inside the curly brackets (this will combine them as a single object) and pass it to the emit method. To receive the parameters in the parent component, we will make a similar type of object and update its value with that of the received object.


1 Answers

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.

like image 192
Günter Zöchbauer Avatar answered Sep 23 '22 13:09

Günter Zöchbauer