Ionic 4 nav.getActive() replacement?

I need a way to get the current page instance from a callback within app.component. Getting url from the router is insufficient, i need the instance so i can invoke page methods.

I’ve search pretty hard and can only find this SO question which does have a potential solution, but it looks more complex than I would like:

Does anybody here have a simpler solution for this?

Hi, Did you get any solution for this?

FWIW, I think this looks like the word “ANTIPATTERN” in giant flashing red lights. The entire point of having pages split out into separate classes is so they enjoy a degree of encapsulation. If you think you want to figure out what page is current from somewhere else random in the app and call some arbitrary method of that page, please: instead, take the time to describe in business/non-technical terms what you really want to achieve. There has got to be a better way for whatever your actual goal is.

Ah, it was for the backbutton handling on Android. For my code I ended up with this in app.component:

      this.platform.backButton.subscribeWithPriority(0, () => {
            // hack to access page method backButtonAction
            // https://stackoverflow.com/questions/51700879/handling-hardware-back-button-in-ionic3-vs-ionic4
            // https://stackoverflow.com/questions/54306319/ionic-4-angular-loops-in-router-history
            const activeView = this.routerOutlet['activated'].instance; // the active view instance
            if (activeView.backButtonAction) {
              activeView.backButtonAction();
            }

Maybe it is an antipattern, I just didn’t want to have to duplicate the backButtonAction() code from each page here. Could have been handled with Ionic Events also I think.

I would do this the other way around - doing the subscription/unsubscription on the back button in the viewDidEnter/viewWillLeave. That way all the relevant code stays in each page, and if the framework decides to do something like disable or disappear the back button when nobody is actively listening to it, your app naturally adjusts and gets these benefits.

1 Like

thanks, I like your suggestion!