Angular2, unsubsribe from event in ngOnDestroy [duplicate] Angular2, unsubsribe from event in ngOnDestroy [duplicate] angular angular

Angular2, unsubsribe from event in ngOnDestroy [duplicate]


You get a subscription from .subscribe(). Use its unsubscribe() method to cancel the subscription.

@Component({  selector: 'receiver',  template: `Count: {{count}}`,})export class ReceiverComponent {  public count = 0;  private subscription;  constructor(private eventService:EventService) {    this.subscription = this.eventService.myEvent.subscribe(() => this.count++;);  }  ngOnDestroy() {    this.subscription.unsubscribe();  }}

See also


I think your should cancel the subscription, as described below:

export class ReceiverComponent {  public count = 0;  private id;  constructor(private eventService:EventService) {    this.id = Date.now();    console.log("ReceiverComponent constructor " + this.id);    this.subscription = this.eventService.myEvent.subscribe(() => {      console.log("count " + this.count + " (id ReceiverComponent instance: " + this.id + ")");      this.count++;    });  }  ngOnDestroy() {    console.log("onDestroy of ReceiverComponent " + this.id)    //this cause "Cannot subscribe to a disposed Subject."    //this.eventService.myEvent.unsubscribe();    this.subscription.unsubscribe();  }}

In fact, EventEmitters are shared observables, i.e. hot observables. Here is a link that could interest you: https://github.com/Reactive-Extensions/RxJS/blob/master/doc/gettingstarted/creating.md.

Hope it helps you,Thierry