How to unsubscribe from EventEmitter in Angular 2?

爷,独闯天下 提交于 2019-12-09 00:28:51

问题


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


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/36494509/how-to-unsubscribe-from-eventemitter-in-angular-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!