首页 文章

处理Ionic3 Vs Ionic4中的硬件后退按钮

提问于
浏览
2

请在 ionic3 中找到以下Android硬件后退按钮操作的代码 . 由于 Ionic4 使用角度路由导航如何为后退按钮发生弹出事件?如果我们想要弹出到最后一页,我们可以使用以下代码 this.navCtrl.goBack('/products'); . 但是如何在 ionic4 中将它用于Android硬件后退按钮操作呢?

Ionic3硬件后退按钮动作

this.platform.registerBackButtonAction(() => {
    let activePortal = this.ionicApp._loadingPortal.getActive() ||
        this.ionicApp._modalPortal.getActive() ||
        this.ionicApp._toastPortal.getActive() ||
        this.ionicApp._overlayPortal.getActive();
    if (activePortal) {
        activePortal.dismiss();
    } else {
        if (this.nav.canGoBack()) {
            ***this.nav.pop();***
        } else {
            if (this.nav.getActive().name === 'LoginPage') {
                this.platform.exitApp();
            } else {
                this.generic.showAlert("Exit", "Do you want to exit the app?", this.onYesHandler, this.onNoHandler, "backPress");
            }
        }
    }
});

2 回答

  • 0

    Update: 这是在dfac9dc中修复的


    Related: ionic4 replacement for registerBackButtonAction


    这是在GitHubIconic ForumTwitter上跟踪的
    在有正式修复之前,您可以使用下面的解决方法 .


    使用 platform.backButton.subscribe (参见here),代码ionic使用its own back button is pressed和新的router-controller一起我们得到这样的东西:

    import {
      IonRouterOutlet,
      Platform,
      ViewChild
    } 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.subscribe(() => {
        if (this.routerOutlet && this.routerOutlet.canGoBack()) {
          this.routerOutlet.pop();
        } else if (this.router.url === '/LoginPage') {
          this.platform.exitApp();
        } else {
          this.generic.showAlert("Exit", "Do you want to exit the app?", this.onYesHandler, this.onNoHandler, "backPress");
        }
      });
    }
    
  • 4

    Try This: app.comonent.ts

    import { Component, ViewChildren, QueryList } from '@angular/core';
    import { Platform, ModalController, ActionSheetController, PopoverController, IonRouterOutlet, MenuController } from '@ionic/angular';
    import { SplashScreen } from '@ionic-native/splash-screen/ngx';
    import { StatusBar } from '@ionic-native/status-bar/ngx';
    import { Router } from '@angular/router';
    import { Toast } from '@ionic-native/toast/ngx';
    
    @Component({
        selector: 'app-root',
        templateUrl: 'app.component.html'
    })
    export class AppComponent {
    
        // set up hardware back button event.
        lastTimeBackPress = 0;
        timePeriodToExit = 2000;
    
        @ViewChildren(IonRouterOutlet) routerOutlets: QueryList<IonRouterOutlet>;
    
        constructor(
            private platform: Platform,
            private splashScreen: SplashScreen,
            private statusBar: StatusBar,
            public modalCtrl: ModalController,
            private menu: MenuController,
            private actionSheetCtrl: ActionSheetController,
            private popoverCtrl: PopoverController,
            private router: Router,
            private toast: Toast) {
    
            // Initialize app
            this.initializeApp();
    
            // Initialize BackButton Eevent.
            this.backButtonEvent();
        }
    
        // active hardware back button
        backButtonEvent() {
            this.platform.backButton.subscribe(async () => {
                // close action sheet
                try {
                    const element = await this.actionSheetCtrl.getTop();
                    if (element) {
                        element.dismiss();
                        return;
                    }
                } catch (error) {
                }
    
                // close popover
                try {
                    const element = await this.popoverCtrl.getTop();
                    if (element) {
                        element.dismiss();
                        return;
                    }
                } catch (error) {
                }
    
                // close modal
                try {
                    const element = await this.modalCtrl.getTop();
                    if (element) {
                        element.dismiss();
                        return;
                    }
                } catch (error) {
                    console.log(error);
    
                }
    
                // close side menua
                try {
                    const element = await this.menu.getOpen();
                    if (element !== null) {
                        this.menu.close();
                        return;
    
                    }
    
                } catch (error) {
    
                }
    
                this.routerOutlets.forEach((outlet: IonRouterOutlet) => {
                    if (outlet && outlet.canGoBack()) {
                        outlet.pop();
    
                    } else if (this.router.url === '/home') {
                        if (new Date().getTime() - this.lastTimeBackPress < this.timePeriodToExit) {
                            // this.platform.exitApp(); // Exit from app
                            navigator['app'].exitApp(); // work in ionic 4
    
                        } else {
                            this.toast.show(
                                `Press back again to exit App.`,
                                '2000',
                                'center')
                                .subscribe(toast => {
                                    // console.log(JSON.stringify(toast));
                                });
                            this.lastTimeBackPress = new Date().getTime();
                        }
                    }
                });
            });
        }
    }
    

    it's work for me, in ionic v4.1.2

相关问题