owlcode
owlcode

Reputation: 51

Unsubscribing from events on page change

When I keep adding pages to navigation stack, more and more instances of SimpleComponent class are created. For this reason I subscribe more than once to "ev" event and fire code more than once.

You can check that by going "there" and "back" in my plunker example and firing event in different situations (check console warnings for results). You can also see that even when you move back to the top of the navigation stack, you still have your subscription.

ionViewWillLeave is not working probably because it's not the actual view that I'm leaving

I wonder what should I do in order to avoid that? I want the SimpleComponent to be included like old-style AngularJS directive as I use it in my application many times.

Here is plunker

export class SimpleComponent {
  constructor(private ev: Events) {
    this.ev.subscribe('ev', e => {
      console.warn(e[0]);
    });  
  }
}


// home.ts template
    <simple-component></simple-component>
    <button (click)="go()">Go next page</button>
    <button (click)="raiseEv()">Raise Event</button>

Upvotes: 3

Views: 3004

Answers (2)

owlcode
owlcode

Reputation: 51

I decided to move my code responsible for handling after-event-received action to @Injectable and that solved the issue

Upvotes: 1

Stefan Svrkota
Stefan Svrkota

Reputation: 50633

You can implement OnDestroy and there you can unsubscribe from ev:

import { OnDestroy } from '@angular/core';

export class SimpleComponent implements OnDestroy {

ngOnDestroy() {
    this.ev.unsubscribe();
}

From Angular 2 documentation:

Put cleanup logic in ngOnDestroy, the logic that must run before Angular destroys the directive. This is the time to notify another part of the application that this component is going away. This is the place to free resources that won't be garbage collected automatically. Unsubscribe from observables and DOM events. Stop interval timers. Unregister all callbacks that this directive registered with global or application services. We risk memory leaks if we neglect to do so.

Upvotes: 7

Related Questions