How to handle back button on Ionic 2

前端 未结 12 1548
野的像风
野的像风 2020-11-29 04:04

How can I handle the back button action on Ionic 2?

I want to be able to know what to do depending on which page is being shown to the user.

I didn\'t find a

12条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-29 04:40

    I found the Easiest way, just add the following code in app.component:

    this.platform.registerBackButtonAction((event) => {
        let activePortal = this.ionicApp._loadingPortal.getActive() ||
        this.ionicApp._modalPortal.getActive() ||
        this.ionicApp._toastPortal.getActive() ||
        this.ionicApp._overlayPortal.getActive();
        if(activePortal && activePortal.index === 0) {
            /* closes modal */
            activePortal.dismiss();
        } else {
            if(this.nav.getActive().name == 'Homepage') {    // your homepage
                this.platform.exitApp();
            }
            else {
                if(this.nav.canGoBack())
                    this.nav.pop();
                this.nav.setRoot(Homepage);
            }
        }
    },101);
    

    That's it! No need to add extra code on every page!

提交回复
热议问题