首页 > 解决方案 > 当用户单击手机后退按钮时,ionic 4 处理模态

问题描述

当用户点击手机的后退按钮时会发生什么?如果模态打开。

注册了一个后退按钮:

// To prevent interference with ionic's own backbutton handling
// you can subscribe with a low priority instead
this.platform.backButton.subscribe(() => {
  // code that is executed when the user pressed the back button
  // and ionic doesn't already know what to do (close modals etc...)
  self.modalController.dismiss();
});

代码的问题:

这不应该发生页面不应该弹出 - 只有模式应该关闭。

检查添加的图像 gif -> 单击此处查看问题

标签: ionic-frameworkionic4ionic-native

解决方案


您可以考虑使用platform.backButton.subscribeWithPriority()高优先级(例如:9999)。

然后检查是否有一个打开的模式modalController.getTop()

constructor(private modalCtrl: ModalController, private nav: NavController) { 
}

ngOnInit() {
  this.platform.backButton.subscribeWithPriority(9999, () => {
    this.closeModalOrPage();
  });
}

async closeModalOrPage(){
  let modal = await this.modalCtrl.getTop();
  if (modal){
    modal.dismiss();
  } else {
    this.nav.pop();
  }
}

推荐阅读