使用ionic2 ionViewCanLeave Navigationguard响应警报以保持或离开页面的好处

Kie*_*yan 3 navigation guard ionic2

目前无法看到使用这样的导航保护点,因为我们不知道要导航到的目标页面(活动页面信息可以从navController getActive()方法获得).通常情况下,我们会使用提醒来询问"你真的想离开这个页面吗?" 为了响应一个菜单选项被选中,例如OK,据我所知,我们不知道"setRoot"哪个页面作为目标页面,因为ionViewCanLeave处理程序没有参数,如toPage/enteringPage.

有没有人设法做到这一点还是宁愿从ionic2目标页面信息中的导航对象中找到?

这里有一些设置上下文的代码:

ionViewCanLeave(): boolean { // no parameters on offer :-( 
    let result: boolean = false;
    let alert: Alert = this._alertCtrl.create({
      title: 'Are you sure you want to leave..?',
      message: 'Your changes will be lost if you do?',
      buttons: [
        {
          text: 'Cancel',
          role: 'cancel',
          handler: () => {
            let dismiss: boolean = true;
            return dismiss;
          }
        },
        {
          text: 'OK',
          handler: () => {
            let dismiss: boolean = false;
            let alertPop = alert.dismiss();
            alertPop
              .then(() => {
                let rootNav: NavController = this._appCtrl.getRootNav();
                this._navCtrl.pop();
                this._navCtrl.setRoot(DashboardPage); // Here we want to parameterize to target page - hardcoded for now
              });
            return dismiss;
          }
        }
      ]
    });
    if (this._applicationService.getOfferStatus() === OfferStatus.live) {
      alert.present();
    }
    return result;
  }
Run Code Online (Sandbox Code Playgroud)

Ale*_*sov 14

不是100%肯定我理解这个问题......但是据我所知,你需要阻止用户根据某些条件导航到某个页面.例如,在编辑表单上,我有以下内容

  ionViewCanLeave() {
    // here we are checking if the dialog is being closed and there are unsaved changes
    if (!this.saved && this.form.dirty) {
      return new Promise((resolve: Function, reject: Function) => {
        this.dialogs.showConfirmDialog('You have unsaved changes. Do you want to close and discard your changes?', null, null, 'confirm-warning-dialog')
          .then((confirmed) => {
            if (confirmed) {
              resolve();
            } else {
              reject();
            }
          });
      });
    }
  }
Run Code Online (Sandbox Code Playgroud)

这将检查表单是否尚未保存并且进行了任何更改后会显示确认对话框.如果在此对话框中取消单击它将阻止导航,否则它允许导航.ionViewCanLeave不会自行导航,但在用户离开页面时用作处理程序.希望这可以帮助

  • 我使用promises工作..你的例子在离子文档中很有用:-) (2认同)