2016-12-29 130 views
14

如何處理離子2上的後退按鈕操作?如何處理離子2上的返回按鈕

我希望能夠知道該做什麼,具體取決於向用戶顯示哪個頁面。

我沒有找到這個問題的一個很好的答案,但過了一段時間,我想出了一個辦法來做到這一點。我會和大家分享一下。

感謝

+0

爲什麼地球上下面這個問題的答案是太辛苦,感覺不一樣實施? :(什麼是最簡單,最簡單的方式? –

回答

22

我是這樣做的:

在每個頁面組件,我創建了一個名爲backButtonAction()功能,這將執行自定義代碼的每一頁。

代碼:

import { Component } from '@angular/core'; 
import { Platform, NavController, ModalController } from 'ionic-angular'; 
import { DetailsModal } from './details'; 

@Component({ 
    selector: 'page-appointments', 
    templateUrl: 'appointments.html' 
}) 
export class AppointmentsPage { 
    modal: any; 

    constructor(private modalCtrl: ModalController, public navCtrl: NavController, public platform: Platform) { 
     // initialize your page here 
    } 

    backButtonAction(){ 
     /* checks if modal is open */ 
     if(this.modal && this.modal.index === 0) { 
      /* closes modal */ 
      this.modal.dismiss(); 
     } else { 
      /* exits the app, since this is the main/first tab */ 
      this.platform.exitApp(); 
      // this.navCtrl.setRoot(AnotherPage); <-- if you wanted to go to another page 
     } 
    } 

    openDetails(appointment){ 
     this.modal = this.modalCtrl.create(DetailsModal, {appointment: appointment}); 
     this.modal.present(); 
    } 
} 

而在app.component.ts,我用platform.registerBackButtonAction方法註冊一個回調將被調用每次單擊後退按鈕。在它內部,我檢查功能backButtonAction是否存在於當前頁面中,並調用它,如果它不存在,則轉到主/第一個選項卡。

如果不需要爲每個頁面執行自定義操作,可以簡化此操作。你可以彈出或退出應用程序。

我這樣做是因爲我需要檢查模式是否在此特定頁面上打開。

代碼:

platform.registerBackButtonAction(() => { 
    let nav = app.getActiveNav(); 
    let activeView: ViewController = nav.getActive(); 

    if(activeView != null){ 
     if(nav.canGoBack()) { 
     nav.pop(); 
     }else if (typeof activeView.instance.backButtonAction === 'function') 
     activeView.instance.backButtonAction(); 
     else nav.parent.select(0); // goes to the first tab 
    } 
    }); 

如果當前頁面是第一個選項卡,應用程序關閉(如在backButtonAction方法定義)。

+0

讓nav = app.getActiveNav(); **這是什麼應用程序** –

+1

它是一個'App'組件的實例,從'ionic-angular'導入 –

+0

我我在我的項目中使用選項卡和sidemenu上述答案工作正常,除了sidemenu部分,當我去頁面窗體sidemenu我無法導航回來我收到組件名稱作爲主頁,即使我在其他頁面時我去側面菜單中的一些頁面,我沒有看到標籤是這個somthing導致錯誤任何幫助如何導航到主頁(tabspage) –

3

按離子2 RC.4文檔從here

您可以使用Platform API的registerBackButtonAction(callback, priority)方法註冊在後退按鈕按下的動作。

當用戶按下本地平臺的後退按鈕(也稱爲「硬件」後退按鈕)時,會觸發後退按鈕事件。此事件僅用於在Android和Windows平臺上運行的Cordova應用程序。此事件不會在iOS上觸發,因爲iOS不具有與Android或Windows設備相同的硬​​件後退按鈕。

註冊硬件後退按鈕操作並設置優先級允許應用程序控制在按下硬件後退按鈕時應調用哪個操作。此方法決定哪些已註冊的後退按鈕操作具有最高優先級並應該被調用。

參數:

  • 回調:功能當按下後退按鈕被調用時,如果該註冊行爲具有最高優先級。
  • 優先:設置此操作的優先級的編號。只有最高優先級纔會執行。默認爲0

返回:功能:,調用它時,將註銷後退按鈕操作的功能。

0

我能夠在我們簡單的設置頁面根的情況下做到這一點...

import {Component, ViewChild, Injector} from '@angular/core'; 
import {Platform, MenuController, Nav, App, IonicApp, NavController} from 'ionic-angular'; 
import {StatusBar} from '@ionic-native/status-bar'; 
import {SplashScreen} from '@ionic-native/splash-screen'; 
import {InvitesPage} from "../pages/invites/invites"; 
import {RewardsPage} from "../pages/rewards/rewards"; 
import {ConnectionsPage} from "../pages/connections/connections"; 
import {MessagesPage} from "../pages/messages/messages"; 
import {ResourcesPage} from "../pages/resources/resources"; 
import {SignoutPage} from "../pages/signout/signout"; 
import {DashboardPage} from "../pages/dashboard/dashboard"; 
import {AccountPage} from "../pages/account/account"; 
import {HomePage} from "../pages/home/home"; 
import {TriviaPage} from "../pages/trivia/trivia"; 
import {Events} from "ionic-angular/util/events"; 


@Component({ 
    templateUrl: 'app.html' 
}) 
export class MyApp { 
    @ViewChild(Nav) nav: NavController; 
    // make HelloIonicPage the root (or first) page 

    public rootPage: any; //if logged in, go to dashboard. 
    public pages: Array<{title: string, component: any}>; 
    public user: any; 
    public routeHistory: Array<any>; 

    constructor(public platform: Platform, 
       public menu: MenuController, 
       public statusBar: StatusBar, 
       public splashScreen: SplashScreen, 
       private _app: App, 
       private _ionicApp: IonicApp, 
       private _menu: MenuController, 
       protected injector: Injector, 
       public _events: Events) { 

    this.initializeApp(); 

    // set our app's pages 
    this.pages = [ 
     {title: 'My Account', component: AccountPage}, 
     {title: 'Dashboard', component: DashboardPage}, 
     {title: 'Invites', component: InvitesPage}, 
     {title: 'Rewards', component: RewardsPage}, 
     {title: 'Connections', component: ConnectionsPage}, 
     {title: 'Messages', component: MessagesPage}, 
     {title: 'Resources', component: ResourcesPage}, 
     {title: 'Trivia', component: TriviaPage}, 
     {title: 'Sign Out', component: SignoutPage} 

    ]; 

    this.routeHistory = []; 
    this.user = {firstName: ''}; 

    } 

    initializeApp() { 

    this.platform.ready().then(() => { 

     this._setupBrowserBackButtonBehavior(); 

     let self = this; 
     if (sessionStorage.getItem('user')) { 
     this.user = JSON.parse(sessionStorage.getItem('user')); 
     self.rootPage = TriviaPage; 
     } else { 
     self.rootPage = HomePage; 
     } 

     this.routeHistory.push(self.rootPage); 
     // Okay, so the platform is ready and our plugins are available. 
     // Here you can do any higher level native things you might need. 
     this.statusBar.styleDefault(); 
     this.splashScreen.hide(); 
    }); 
    } 

    openPage(page) { 
    // close the menu when clicking a link from the menu 
    this.menu.close(); 
    // navigate to the new page if it is not the current page 
    this.nav.setRoot(page.component); 
    //store route history 
    this.routeHistory.push(page.component); 
    } 


    private _setupBrowserBackButtonBehavior() { 

    // Register browser back button action(s) 
    window.onpopstate = (evt) => { 

     // Close menu if open 
     if (this._menu.isOpen()) { 
     this._menu.close(); 
     return; 
     } 

     // Close any active modals or overlays 
     let activePortal = this._ionicApp._loadingPortal.getActive() || 
     this._ionicApp._modalPortal.getActive() || 
     this._ionicApp._toastPortal.getActive() || 
     this._ionicApp._overlayPortal.getActive(); 

     if (activePortal) { 
     activePortal.dismiss(); 
     return; 
     } 

     if (this.routeHistory.length > 1) { 
     this.routeHistory.pop(); 
     this.nav.setRoot(this.routeHistory[this.routeHistory.length - 1]); 
     } 


    }; 

    // Fake browser history on each view enter 
    this._app.viewDidEnter.subscribe((app) => { 
     if (this.routeHistory.length > 1) { 
     history.pushState(null, null, ""); 
     } 

    }); 

    } 
} 
4

離子最新3.xx版app.component.ts文件import { Platform, Nav, Config, ToastController} from 'ionic-angular';

constructor(public toastCtrl: ToastController,public platform: Platform) { 
platform.ready().then(() => { 
     //back button handle 
     //Registration of push in Android and Windows Phone 
     var lastTimeBackPress=0; 
     var timePeriodToExit=2000; 

    platform.registerBackButtonAction(() => { 
    // get current active page 
     let view = this.nav.getActive(); 
    if(view.component.name=="TabsPage"){ 
        //Double check to exit app     
        if(new Date().getTime() - lastTimeBackPress < timePeriodToExit){ 
         this.platform.exitApp(); //Exit from app 
        }else{ 
         let toast = this.toastCtrl.create({ 
          message: 'Press back again to exit App?', 
          duration: 3000, 
          position: 'bottom' 
          }); 
          toast.present();  
          lastTimeBackPress=new Date().getTime(); 
        } 
    }else{ 
     // go to previous page 
       this.nav.pop({}); 
    } 
    }); 

}); 

} 
0

我找到了最簡單的方法,只需在中添加如下代碼:

this.platform.registerBackButtonAction((event) => { 
    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(); 
    } else { 
     if(this.nav.getActive().name == 'Homepage') { // your homepage 
      this.platform.exitApp(); 
     } 
     else { 
      if(this.nav.canGoBack()) 
       this.nav.pop(); 
      this.nav.setRoot(Homepage); 
     } 
    } 
},101); 

這就是它! 無需在每個頁面上添加額外的代碼!

3

我用這裏和其他來源的答案來完成我所需要的。 我注意到,當你建立生產(--prod)應用這種方法是行不通的,因爲JS uglifying和簡化:

this.nav.getActive().name == 'PageOne' 

正因爲如此,我在「如果」語句中使用下一個:

view.instance instanceof PageOne 

所以最終的代碼如下所示:長期搜索後

this.platform.ready().then(() => { 

    //Back button handling 
    var lastTimeBackPress = 0; 
    var timePeriodToExit = 2000; 
    this.platform.registerBackButtonAction(() => { 
    // get current active page 
    let view = this.nav.getActive(); 
    if (view.instance instanceof PageOne) { 
     if (new Date().getTime() - lastTimeBackPress < timePeriodToExit) { 
      this.platform.exitApp(); //Exit from app 
     } else { 
     let toast = this.toastCtrl.create({ 
      message: 'Tap Back again to close the application.', 
      duration: 2000, 
      position: 'bottom', 
     }); 
     toast.present();  
     lastTimeBackPress = new Date().getTime(); 
     } 
    } else if (view.instance instanceof PageTwo || view.instance instanceof PageThree) { 
     this.openPage(this.pages[0]); 
    } else { 
     this.nav.pop({}); // go to previous page 
    } 
    }); 
}); 
0

最佳實踐的解決方案。

它的工作原理100%,並在真實設備

this.Platform.registerBackButtonAction(() => { 
 
      // try to dismiss any popup or modal 
 
      console.log("Back button action called"); 
 

 
      let activePortal = this.ionicApp._loadingPortal.getActive() || 
 
      this.ionicApp._modalPortal.getActive() || 
 
      this.ionicApp._toastPortal.getActive() || 
 
      this.ionicApp._overlayPortal.getActive(); 
 

 
      if (activePortal) { 
 
      // ready = false; 
 
      activePortal.dismiss(); 
 
      activePortal.onDidDismiss(() => { }); 
 

 
      console.log("handled with portal"); 
 
      return; 
 
      } 
 

 
      // try to close the menue 
 

 
      if(this.MenuController.isOpen()){ 
 
      this.closeMenu(); 
 
      return; 
 
      } 
 
      else if(this.nav.canGoBack()){ 
 
      this.nav.pop(); 
 
      return; 
 
      }else{ 
 

 
      let activePage = this.nav.getActive().instance; 
 

 
      let whitelistPages = [LoginPage, HomePage]; 
 

 
      // if current page is not in whitelistPage 
 
      // then back to home or login page first 
 
      if (whitelistPages.indexOf(activePage.constructor) < 0) { 
 
       this.nav.setRoot(this.userLoggedIn ? HomePage : LoginPage); 
 

 
       return; 
 
      }else if(whitelistPages.indexOf(activePage.constructor) > 0){ 
 
       this.AppUtilities.showConfirm("Exit","Are you want to exist the app ? ").subscribe(
 
       ()=>{ 
 
        this.Platform.exitApp(); 
 
       }, 
 
       ()=>{} 
 
      ) 
 
      }else{ 
 
       console.error('cannot handel back button') 
 
      } 
 

 

 
      } 
 

 
     });

0

我有輕微的不同的方法與@amr阿卜杜勒阿齊茲比較測試它。我使用setTimeout來控制返回或退出。希望這會爲實現後退按鈕提供另一種選擇。

initBackButtonBehaviour() { 
 
    this.platform.registerBackButtonAction(() => { 
 
     console.log("Back button pressed"); 
 
     if (this.readyToExit) { 
 
     this.platform.exitApp(); 
 
     return; 
 
     } 
 

 
     let activePortal = this.ionicApp._loadingPortal.getActive() || 
 
     this.ionicApp._modalPortal.getActive() || 
 
     this.ionicApp._toastPortal.getActive() || 
 
     this.ionicApp._overlayPortal.getActive(); 
 

 
     if (activePortal) { 
 
     activePortal.dismiss(); 
 
     activePortal.onDidDismiss(() => { }); 
 

 
     return; // stop any further action after closing any pop up modal or overlay 
 
     } 
 

 
     if (this.menuCtrl.isOpen()) { 
 
     this.menuCtrl.close(); 
 
     return; // stop any further action after menu closed 
 
     } 
 
     else if (this.nav.canGoBack()) { 
 
     this.nav.pop(); 
 
     return; // stop any further action after navigation pop 
 
     } 
 
     else { 
 
     let activePage = this.nav.getActive().instance; 
 

 
     let whiteListPages = [HomePage]; 
 

 
     // if current page is not in whitelistPage 
 
     // then back to home or login page first 
 
     if (whiteListPages.indexOf(activePage.constructor) < 0) { 
 
      this.nav.setRoot(HomePage); 
 

 
      return; 
 
     } else if (whiteListPages.indexOf(activePage.constructor) >= 0) { 
 
      this.utils.showToast('Press back button again to exit', 1500); 
 

 
      this.readyToExit = true; 
 
      setTimeout(() => { 
 
      this.readyToExit = false; 
 
      }, 1500); 
 

 
     } else { 
 
      console.error('cannot handle back button'); 
 
     } 
 

 
     } 
 
    }, 101);