Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hardware back button closes the app on Tab enabled Ionic 3 app

When the user hits my profile page(or tab), the user is not logged in then it shows login page as shown below.On the login page where it has header back button and it is working fine (you can see the code below).I need the same functionality when the user hits the hardware back button on Android device.But it closes the app.Can you tell me how to solve this issue? If you need more info please let me know.

my-profile.ts

constructor(public navCtrl: NavController, public app: App, public userService: UserService
        ) {
        if (!this.userService.userDetails) {
            this.app.getRootNav().setRoot('Login', { profile: true });
            return;
        }
    }

login.ts

constructor(public navCtrl: NavController, public navParams: NavParams) {
        this.profile = this.navParams.data.profile;
    }

    back() {
        if (this.profile) {//not logged in user
            this.navCtrl.setRoot('TabsPage');
        }
    }

login.html

<ion-header>
  <ion-navbar>
    <ion-buttons left>
      <button ion-button *ngIf="profile" (click)="back()" tappable><ion-icon name="arrow-back"></ion-icon></button>
    </ion-buttons>
    <ion-title>login</ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>

</ion-content>
like image 895
Sampath Avatar asked Jul 14 '17 11:07

Sampath


2 Answers

Just set the property navExitApp to false in file app.module.ts at imports

IonicModule.forRoot(YourApp, {
  navExitApp: false
}),

Easy! You do not need to touch the registerBackButtonAction event.

like image 181
Dominik Avatar answered Sep 24 '22 05:09

Dominik


You can use the Platform's registerBackButtonAction() method to handle when the user press the native back button.

import { Platform } from 'ionic-native';
...
constructor(public platform: Platform){

  platform.registerBackButtonAction(() => {
    if (navCtrl.canGoBack()) { // CHECK IF THE USER IS IN THE ROOT PAGE.
      navCtrl.pop(); // IF IT'S NOT THE ROOT, POP A PAGE.
    } else {
      platform.exitApp(); // IF IT'S THE ROOT, EXIT THE APP.
    }
  });

}

But the case here is that you're setting roots and not pushing pages, so this is the normal behaviour of Ionic, when in root page and there's nothing to pop to, the app is closed.

In this case you can do something like this on your login.ts

platform.registerBackButtonAction(() => {
  this.back();
});

So every time the user is in the login page and hits the hardware back button it simply call your back() method that'll set the root to another page.

Hope this helps.

like image 28
Gabriel Barreto Avatar answered Sep 22 '22 05:09

Gabriel Barreto