Ionic 2: How to handle the hardware back button which checks confirmation of Exit in app

前端 未结 7 608
你的背包
你的背包 2020-12-05 06:12

I am facing an issue how to handle the default mobile\'s back button which checks the confirmation while exiting from the application, if I pressed the back button there sho

相关标签:
7条回答
  • 2020-12-05 06:55

    I managed to create this function by doing a lot of research. Hope it helps.

        // I am using this.isExitAlertOpen just to make sure that the alert does not open if already open.
    
        handleBackButton() {
        this.platform.registerBackButtonAction(() => {
            // const activePortal =
            // this.ionicApp._modalPortal.getActive() ||
            // this.ionicApp._loadingPortal.getActive() ||
            // this.ionicApp._toastPortal.getActive() ||
            // this.ionicApp._overlayPortal.getActive();
    
            // console.warn('ACTIVE PORTALS', activePortal);
    
            const activeModal = this.ionicApp._modalPortal.getActive();
            console.warn('MODAL', activeModal);
    

    activePortal can be used to find the relevant active portals which includes alert, loader, modal, etc. If you want to handle everything with the back button or some of them uncomment according to your usage

    In my case I only wanted to check if modal was active so I checked only for modal.

            //  if (activePortal) {
            //    activePortal.dismiss();
            //  }
    
            if (activeModal) {
                activeModal.dismiss();
            } else if (this.nav.canGoBack()) {
                this.nav.pop();
            } else {
                if (this.isExitAlertOpen) return;
                this.isExitAlertOpen = true;
                this.showExitAlert();
            }
        });
    }
    
    showExitAlert() {
        this.alertCtrl.create({
            title: 'Exit',
            message: 'Are you sure you want to exit the app?',
            enableBackdropDismiss: false,
            buttons: [
                {
                    text: 'Yes',
                    handler: () => {
                        this.isExitAlertOpen = false;
                        this.platform.exitApp();
                    }
                }, {
                    text: 'Cancel',
                    role: 'cancel',
                    handler: () => {
                        this.isExitAlertOpen = false;
                    }
                }
            ]
        }).present();
    }
    
    0 讨论(0)
提交回复
热议问题