Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

To close the app from particular page on single tap of hardware back button

My app consists of 2 pages called login, home and other lazy loaded modules. In the app.component.ts, condition is written such that if localStorage is empty it should route to login page else it should route to home page. Then from home page user will routed other lazy loaded modules

app.component.ts

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

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

      constructor(
        private splashScreen: SplashScreen,
        private statusBar: StatusBar,
        private platform: Platform,
        public navCtrl: NavController,
      ) {
        this.initializeApp();
        if (localStorage.getItem('token') !== null) {
          this.navCtrl.navigateRoot('/home');
        } else {
          this.navCtrl.navigateRoot('/login');
        }
      }

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


    }

app-routing.module.ts

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

    const routes: Routes = [

      {path: 'home',loadChildren: './home/home.module#HomePageModule'},
      { path: 'login', loadChildren: './login/login.module#LoginPageModule' },
      { path: '', loadChildren: './nav-bar/nav-bar.module#NavBarPageModule' },  <===== Lazy loaded module
      { path: '', loadChildren: './nav-bar-provider/nav-bar-provider.module#NavBarProviderPageModule' }, <===== Lazy loaded module
    ];

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

This condition works fine. Then in the home page I have written code to exit from the app on double-tap as shown below:

home.page.ts

    import { Component , OnInit} from '@angular/core';
    import { Platform } from '@ionic/angular';
    @Component({
      selector: 'app-home',
      templateUrl: 'home.page.html',
      styleUrls: ['home.page.scss'],
    })
    export class HomePage implements OnInit {
      subscription;
      constructor(public platform: Platform) {}

      ngOnInit() {}

      ionViewDidEnter() {
        this.subscription = this.platform.backButton.subscribe(() => {
          (navigator as any).app.exitApp();
        });
      }
      ionViewDidLeave() {
        this.subscription.unsubscribe();
      }
    }

Now the issues is: On double tap in home page,the app will close, But on single tap it will routed 1st lazy loaded module(i,e NavBarPageModule). How can avoid this? For this issue, I tried giving router-path to lazy loaded modules like this:

    const routes: Routes = [

      {path: 'home',loadChildren: './home/home.module#HomePageModule'},
      { path: 'login', loadChildren: './login/login.module#LoginPageModule' },
      { path: 'nav-bar', loadChildren: './nav-bar/nav-bar.module#NavBarPageModule' }, 
      { path: 'nav-bar-provider', loadChildren: './nav-bar-provider/nav-bar-provider.module#NavBarProviderPageModule' },
    ];

Then I was unable to route to lazy loaded modules from home page.

I just want to close the app from home page on single tap.

like image 800
PGH Avatar asked Sep 12 '19 07:09

PGH


2 Answers

I am posting the solution which worked for me, It may help for other users.

app.component.ts file should look like this:

import { Component } from '@angular/core';
import { Platform, ToastController } from '@ionic/angular';
@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html'
})
export class AppComponent {
  counter = 0;

  constructor(
              public platform: Platform,
              public toastController: ToastController
  ) { 
    this.platform.ready().then(() => {
      document.addEventListener('backbutton', async () => {
          if (this.counter === 0) {
            this.counter++;
            this.alertToast();
            setTimeout(() => { this.counter = 0; }, 3000);
          } else {
            (navigator as any).app.exitApp();
          }
      });
    });
  }

  async alertToast() {
    const toast = await this.toastController.create({
      message: 'Press again to exit',
      duration: 300,
      position: 'middle',
    });
    toast.present();
  }


}
like image 153
PGH Avatar answered Oct 13 '22 18:10

PGH


Try this:

document.addEventListener('backbutton', function(event){
  event.preventDefault();
  navigator.app.exitApp(); // exit the app
});

I hope this will help you.

like image 31
Anand Gupta Avatar answered Oct 13 '22 18:10

Anand Gupta