Search code examples
javascriptangulartypescriptionic2hybrid

Getting multiple instance of same modal in ionic 2/3


Inside my app.component , I have a background mode service which when shared via intent throws value to a behaviour Subject

this._notification.setNotiService2(data.extras);

Once logged In , I am setting the root to TabsPage

this.appCtrl.getRootNav().setRoot('TabsPage');

On Tabs Page , I have subscribed to the behaviour subject , so whenever I get a shared object , I process it and open a Modal displaying the required values. Initally when the app opens , everything works fine. But once we login/logout the problem occurs. On logging out , I am setting the root page as Login Page.

this.appCtrl.getRootNav().setRoot('LoginPage');

Then again on successful login setting root to Tabs Page

 this.appCtrl.getRootNav().setRoot('TabsPage');

Now again if I share the values via intent multiple instances of the Modal are opening with the exact same values. I have checked for behaviour subject as being null/undefined but the subscribed value is Ok only . Logging the value from behaviour Subject inside the TabsPage , I found the same function (subscribed behaviour subject) is being called twice.

Again if I logout/login the Modal opens 3 times and the number continues to grow accordingly.


Solution

  • It sounds to me, that you are not remembering to unsubscribe, which means that the subscriptions increment each time. So whenever you leave a page, remember to unsubscribe to (all) your subscriptions. Since you are using Ionic, the ionViewWillLeave hook would be a suitable place to unsubscribe... so declare a new Subscription on your page and...

    import { Subscription } from 'rxjs/Subscription';
    
    // ...
    
    mySubscription = new Subscription();
    
    // ...
    
    this.mySubscription = this.myService.mySubject.subscribe(....)
    
    // ...  
    
    ionViewWillLeave() { 
      this.mySubscription.unsubscribe();
    }