问题
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