jdubicki
jdubicki

Reputation: 399

Ionic 4 hadware back button routing

I am having a routing issue in Ionic 4 Beta 15 and was hoping someone could help me solve it. My Ionic 4 app has a side menu with 4 pages in it. One of those pages is call Home and it is the starting page of the app. I want to be able to go back to that page when the user hits the hardware back button when they are in one of the side menu pages. Furthermore that home page is made up of 3 tabs that have their own routing. I would also like to be able to send the user to that first to the first tab of the home page. I have tried using the various methods of Router as well as NavController, and I always have an issue with the history stack. I have included my app.components page with the desired out come based on what page you are on. Please help, I have been banging my head for weeks.

app.components.ts

import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { Platform } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html'
})
export class AppComponent {

  public appPages = [
    {
      title: 'Home',
      url: ''
    },
    {
      title: 'Bible',
      url: '/bible'
    },
    {
      title: 'Map',
      url: '/map'
    },
    {
      title: 'Give',
      url: '/give'
    }
  ];

  constructor(private router: Router,
    private platform: Platform,
    private splashScreen: SplashScreen,
    private statusBar: StatusBar) {
    this.initializeApp();
    this.hardwareBackButton();
  }

  initializeApp() {
    this.platform.ready().then(() => {
      this.statusBar.styleDefault();
      this.splashScreen.hide();
    });
  }

  hardwareBackButton() {
    this.platform.backButton.subscribe(async () => {
      console.log(this.router.url);
      let url = this.router.url;

  switch (url) {
    case '/tabs/(messages:messages)':
      // This works like I want it to
      // When you are at the /tabs/(messages:messages) page and the back 
      // button it his, the app will exit
      navigator['app'].exitApp();
      break;
    case '/tabs/(e3:e3)':
      // Here I want to navigate to /tabs/(messages:messages) page
      break;
    case '/tabs/(prayers:prayers)':
      // Here I want to navigate to /tabs/(messages:messages) page
      break;
    case '/bible':
      // Here I want to navigate to /tabs/(messages:messages) page
      break;
    case '/map':
      // Here I want to navigate to /tabs/(messages:messages) page
      break;
    case '/give':
      // Here I want to navigate to /tabs/(messages:messages) page
      break;
  }
    });
  }

}

app-routing.modules.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

const routes: Routes = [
  {
    path: '',
    loadChildren: './tabs/tabs.module#TabsPageModule'
  },
  {
    path: 'bible',
    loadChildren: './bible/bible.module#BiblePageModule'
  },
  {
    path: 'map',
    loadChildren: './map/map.module#MapPageModule'
  },
  {
    path: 'give',
    loadChildren: './give/give.module#GivePageModule'
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {}

tabs.router.module.ts

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { TabsPage } from './tabs.page';
import { MessagesPage } from '../messages/messages.page';
import { E3Page } from '../e3/e3.page';
import { PrayersPage } from '../prayers/prayers.page';

const routes: Routes = [
  {
    path: 'tabs',
    component: TabsPage,
    children: [
      {
        path: '',
        redirectTo: '/tabs/(messages:messages)',
        pathMatch: 'full',
      },
      {
        path: 'messages',
        outlet: 'messages',
        component: MessagesPage
      },
      {
        path: 'e3',
        outlet: 'e3',
        component: E3Page
      },
      {
        path: 'prayers',
        outlet: 'prayers',
        component: PrayersPage
      }
    ]
  },
  {
    path: '',
    redirectTo: '/tabs/(messages:messages)',
    pathMatch: 'full'
  }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class TabsPageRoutingModule {}

Any help is greatly appreciated.

Upvotes: 1

Views: 1214

Answers (1)

athulpraj
athulpraj

Reputation: 1577

Override the default hardware back button in ionic 4 using the following

In your app.copmponent.ts constructor, subscribe to the back button event

For action sheet, modal, popover etc ... define the intended actions

At last use navctrl to pop to the previous page (works with angular routing)

import { ....,NavController} from '@ionic/angular';

consructor(.....,public nav : NavController)
{
  this.backButtonEvent()
}

backButtonEvent() {
   this.platform.backButton.subscribeWithPriority(9999, async () => {
     try {
       const element = await this.actionSheetCtrl.getTop();
       if (element) { element.dismiss(); return }
     } catch (error) {}
     try { 
           const element = await this.popoverCtrl.getTop();
           if (element) { element.dismiss(); return }
         } catch (error) {}
     try {
           const element = await this.modalCtrl.getTop();
           if (element) { element.dismiss(); return }
         } catch (error) { }
     try {
           const element = await this.alertController.getTop();
           if (element) { element.dismiss(); return }
         } catch (error) { }
     } 
     this.nav.pop() 
   });
}

Upvotes: 0

Related Questions