Remove subscriptions when leaving page



is there a “way to go” to trigger subscriptions only as long as the page contianing a content is visible?
my listener looks like this:
this.sharedService.myEvent.subscribe(myEventData => { ... });

Now I can’t find a good method to unsubscribe this. No method I tried works on page push and pop.

I would like to have some global events to trigger when gaining network connection, triggering a pull to refresh, etc.
These events should be listened to inside multiple components so that they can do their required actions.
Seemed to work fine until I recognized, that the subscriptions are kept alive, event when I change the page.

Every idea for a better solutions is welcome! :slight_smile:



ionViewDidLeave(). I have an array I want to repopulate exactly when the page is active, so I subscribe in ionViewWillEnter(), and in ionViewDidLeave I use splice to reset the array length to 0, and unsubscribe from the Observable.


unfortunately these methods are only available on a page but not inside a component.
But you can subscribe to the events with the NavController like this:

this.navCtrl.viewWillLeave.subscribe(() => { ... });

It’s not the finest way as you would have to set a subsription to remove another subscription, but I can’t think of any other way. :confused:
Also there is no event which triggers on every pageleave (setRoot, push, pop, back).


@AaronSterling ok seems like my events get triggered on enter too. so I get my “leave”-events when entering the page which is of course not nice. any idea how to prevent this?


If you want an event to occur exactly once, on initiialization, put it in the page’s constructor. Could you use dependency injection with your component so the subscription part at least becomes part of the page constructor, if you only have to read once? Also, have you seen this?


thanks, the link brought some light into the issue.
I will give it a try when I have time.
What exactly do you mean with

use dependency injection with your component so the subscription part at least becomes part of the page constructor

Could you give a rough example in code? :slight_smile:


I just mentioned what I’d try if I had that issue. I don’t have code to give you off the top of my head. That’s why I was asking a question, not saying what to do. The Angular page on Dependency Injection provides several code examples, but nothing with Observables I don’t think. It sounded as though you wanted to subscribe exactly when your page is initialized, so I thought that might work.


I got something like this:

counter() {
return Observable
  .do(() => {

this.messagesLoader = this.counter().subscribe();


This is working fine for me.