Handling hardware back button in Ionic3 Vs Ionic4

前端 未结 6 1586
悲哀的现实
悲哀的现实 2020-12-01 09:30

Please find the below code for the Android hardware back button action in ionic3. As Ionic4 uses angular routing for navigation how the pop event w

6条回答
  •  伪装坚强ぢ
    2020-12-01 10:22

    Update: This was fixed in v4.0.0-beta.8 (dfac9dc)


    Related: ionic4 replacement for registerBackButtonAction


    This is tracked on GitHub, in the Iconic Forum and Twitter
    Until there is an official fix, you can use the workaround below.


    Using platform.backButton.subscribe (see here) platform.backButton.subscribeWithPriority(0, ...) to let ionic handle closing all the modals/alerts/... , the code ionic uses when its own back button is pressed and the new router-controller together we get something like this:

    import { ViewChild } from '@angular/core';
    import { IonRouterOutlet, Platform } from '@ionic/angular';
    import { Router } from '@angular/router';
    
    //...
    
    /* get a reference to the used IonRouterOutlet 
    assuming this code is placed in the component
    that hosts the main router outlet, probably app.components */
    @ViewChild(IonRouterOutlet) routerOutlet: IonRouterOutlet;
    
    constructor(
      ...
      /* if this is inside a page that was loaded into the router outlet,
      like the start screen of your app, you can get a reference to the 
      router outlet like this:
      @Optional() private routerOutlet: IonRouterOutlet, */
      private router: Router,
      private platform: Platform
      ...
    ) {
      this.platform.backButton.subscribeWithPriority(0, () => {
        if (this.routerOutlet && this.routerOutlet.canGoBack()) {
          this.routerOutlet.pop();
        } else if (this.router.url === '/LoginPage') {
          this.platform.exitApp(); 
    
          // or if that doesn't work, try
          navigator['app'].exitApp();
        } else {
          this.generic.showAlert("Exit", "Do you want to exit the app?", this.onYesHandler, this.onNoHandler, "backPress");
        }
      });
    }

提交回复
热议问题