How to handle back button on Ionic 2

前端 未结 12 1533
野的像风
野的像风 2020-11-29 04:04

How can I handle the back button action on Ionic 2?

I want to be able to know what to do depending on which page is being shown to the user.

I didn\'t find a

12条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-29 04:54

    In Ionic 3 Lazy Loading, I never felt the need of Handling back behavior of browser where as for platform.is('cordova') I have created following method which handles all back scenarios:

    // If a view controller is loaded. Just dismiss it.
    let nav = this.app.getActiveNav();
    let activePortal = this._ionicApp._loadingPortal.getActive() ||
    this._ionicApp._modalPortal.getActive() ||
    this._ionicApp._toastPortal.getActive() ||
    this._ionicApp._overlayPortal.getActive();
    if(activePortal && activePortal.index === 0) {
        /* closes modal */
        activePortal.dismiss();
        return;
    }
    
    // If a state is pushed: Pop it.
    if (this.nav.canGoBack()) {
      this.nav.pop();
      return;
    } else 
    // Else If its a tabs page: 
    if (this.nav.getActiveChildNav()) {     
        const tabs: Tabs = this.nav.getActiveChildNav();
        const currentTab = tabs.getActiveChildNavs()[0];
        // If any page is pushed inside the current tab: Pop it
        if(currentTab.canGoBack()) {
          currentTab.pop();
          return;
        }
        else 
        // If home tab is not selected then select it.
        if(tabs.getIndex(currentTab) !=0){
          tabs.select(0);
          return;
        }
    }
    else 
    // If a menu is open: close it.
    if (this.menu.isOpen()) {
      this.menu.close();
      return;
    }
    
    
    
    
    if (this.exitApp) {
      this.platform.exitApp();
      return;
    }
    this.exitApp = true;
    
    const toast = this.toastCtrl.create({
      message: this.exitMessage || 'press again to exit',
      duration: 4000,
      position: 'bottom',
      cssClass: 'exit-toastr',
    });
    toast.present();
    setTimeout(() => {
      this.exitApp = false;
    }, 2000);
    

提交回复
热议问题