Reputation: 213
When I built and ran my app on android, I realized that the hardware back button is not working. I Have the main page, which has two children, a home and a favorite page, where the home page is the default page. If I am at the Favourites page and I click the back button, it takes me to the home page, but from the home page, if I click the back button, it shows a white screen and restarts the app after few seconds. I would only be able to close the app if I click it three times. I am using ionic 4, Angular 8.
Here is how my app route looks like:
{ path: '', loadChildren: './pages/main/main.module#MainPageModule' },
{ path: 'search', loadChildren:
'./pages/search/search.module#SearchPageModule' },
{ path: 'catalog-view', loadChildren: './pages/cat-view/cat-
view.module#CatViewPageModule' },
and here is what my main module looks like:
const routes: Routes = [
{
path: 'main',
component: MainPage,
children: [
{ path: 'home', loadChildren: '../home/home.module#HomePageModule' },
{ path: 'favorites', loadChildren:
'../favorites/favorites.module#FavoritesPageModule' },
]
},
{
path: '',
redirectTo: '/main/home'
}
];
I tried to add this functionality at the homePage, then the Main, and even the Appcompomponent, but nothing works:
ionViewDidEnter(){
this.subscription = this.platform.backButton.subscribe(()=>{
navigator['app'].exitApp();
});
}
ionViewWillLeave(){
this.subscription.unsubscribe();
}
Upvotes: 2
Views: 2645
Reputation: 213
I got it working, the problem was very silly. I had to update my packages to the latest version, especially the @ionic-native/core. and in my home.ts i just simply do this:
ngOnInit(){
this.platform.backButton.subscribe(() => {
this.platform.backButton.unsubscribe();
navigator['app'].exitApp();
})
)
Hope it helps!
Upvotes: 2
Reputation: 160
I have the following code in my home page, het registers a different function to the back button while on the home page. and then deregister it again as soon as it leaves.
private isToastShown: boolean = false;
ionViewDidEnter(){
/* When on home page the back button should confirm before exiting */
this.platform.backButton.subscribeWithPriority(0, () => {
if (!this.isToastShown) {
this.presentConfirm();
} else {
navigator['app'].exitApp();
}
}, 0);
}
ionViewWillLeave() {
/* Reset back button to pop pages when pressed */
this.aPlatform.registerBackButtonAction(() => {
if (this.aNavController.canGoBack()) {
this.aNavController.pop();
}
});
}
private presentConfirm(): void {
this.isToastShown = true;
let lToast = this.aToastController.create({
message: "Press back again to exit"
});
lToast.present().then(() => {
setTimeout(() => {
lToast.dismiss();
this.isToastShown = false;
}, 2000);
});
}
Hope this helps
Upvotes: 1