如何处理Ionic 2上的后退按钮 [英] How to handle back button on Ionic 2
问题描述
如何处理Ionic 2上的后退按钮操作?
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 good answer to this question, but after a while I figured it out myself a way to do it. I'm gonna share with you all.
谢谢
推荐答案
我是这样做的:
在每个Page组件中,我创建了一个名为 backButtonAction()
的函数,为每个页面执行自定义代码。
In every Page component, I created a function called backButtonAction()
, which will execute custom code for every page.
代码:
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();
}
}
并在应用中。 component.ts
,我使用 platform.registerBackButtonAction
方法来注册每次单击后退按钮时都会调用的回调。在其中我检查当前页面中是否存在函数 backButtonAction
并调用它,如果它不存在,只需转到主/第一个选项卡。
And in the app.component.ts
, I used the platform.registerBackButtonAction
method to register a callback that will be called everytime the back button is clicked. Inside it I check if the function backButtonAction
exists in the current page and call it, if it doesn't exists, just go to the main/first tab.
如果他们不需要为每个页面执行自定义操作,可以简化此操作。您可以弹出或退出应用程序。
One could simplify this if they didn't need to perform customized actions for every page. You could just pop or exit the app.
我这样做是因为我需要检查模态是否在此特定页面上打开。
I did it this way because I needed to check if the modal was open on this particular page.
代码:
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
}
});
如果当前页面是第一个标签,则应用关闭(如<$ c $中所定义) c> backButtonAction 方法)。
if the current page is the first tab, the app closes (as defined in the backButtonAction
method).
这篇关于如何处理Ionic 2上的后退按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!