1
votes

using ionic 4 i have created an application in that i need to control back button. I have used the following code

this.backButtonSubscription = 
this.platform.backButton.subscribeWithPriority(1, async  () => {
    if (this.router.url === '/registration') {
        navigator['app'].exitApp();
    }
});

This subscription event is working only on root page and not working on other pages.

I want to control the back button on particular page to show alert and other things, but right now when clicking hardware back button in android device it goes to the previous page.

2

2 Answers

0
votes

Code below works for me absolutely fine.

In initializeApp() method in app.component.ts

initializeApp() {
    this.platform.ready().then(() => {
      this.statusBar.styleLightContent();
      this.splashScreen.hide();
      this.platform.backButton.subscribeWithPriority(9999, () => {
        if(this.router.url !== '/login') {
          // Back button controls when user is not in Login Page
        } else {
          navigator['app'].exitApp();
        }
      });
    });
  }
0
votes

if you want the backButton to do Alert or Toast

Create the backButton function:

backButton() {
    this.platform.backButton.subscribeWithPriority(0, () => {
        this.showAlertBack();
    });
}

Create the Alert Function:

async showAlertBack() {
        const alert = await this.alertCtrl.create({
            message: 'Want to Exit App?',
            buttons: [
                {
                    text: 'Ok',
                    handler: () => {
                        navigator['app'].exitApp();
                    }
                },
                {
                    text: 'Nop',
                    handler: () => {
                        alert.dismiss();
                    }
                }
            ],
            backdropDismiss: false
        });
        await alert.present();
    }

Now Initialize it in ngOnInit() or ionViewWillEnter()

this.backButton();