如何在Ionic中更换标签时使用导航保护?

Mik*_*ike 8 tabs typescript ionic-framework ionic2 angular

我正在使用Ionic 2.我认为应该提示用户在导航时确认他们想要离开(当时播放视频,这可能是偶然的导航).

当用户使用以下代码单击顶部导航中的后退按钮或后退硬件按钮(Android)时,我可以正常工作:

  // About to leave
  ionViewCanLeave() {
    this.api.getDefaultMedia().pause();

    return new Promise((resolve, reject) => {
      if(!this.allowedToLeave) {
        let confirm = this.alertCtrl.create({
          title: 'Are you sure?',
          message: 'If you leave a class you will need to start over.  Are you sure you want to leave?  If you need a break you can pause by tapping the video.',
          buttons: [{
            text: 'OK',
            handler: () => {
              this.allowedToLeave = true;
              resolve();
            },
          }, {
            text: 'Cancel',
            handler: () => {
              reject();
            }
          }],
        });
        confirm.present();
      }
    });
  }
Run Code Online (Sandbox Code Playgroud)

视图位于选项卡中.单击其他选项卡不会调用此功能,因此不会提示用户,并且选项卡只会切换.

如何更改选项卡上显示的此提示?该视图不是根标签页.

-

我已经尝试使用ionViewWillLeave(),这称为一个标签的变更,但不允许的方式来阻止用户切换.下面的代码确实显示了提示,但是在选项卡更改后:

  // Called when user exits page via tab
  ionViewWillLeave() {
    this.api.getDefaultMedia().pause();

    if(!this.allowedToLeave) {
      let confirm = this.alertCtrl.create({
        title: 'Are you sure?',
        message: 'If you leave a class you will need to start over.  Are you sure you want to leave?  If you need a break you can pause by tapping the video.',
        buttons: [{
          text: 'OK',
          handler: () => {
            this.allowedToLeave = true;
            this.leave();
          },
        }, {
          text: 'Cancel',
          handler: () => {
            // Do nothing
          }
        }],
      });
      confirm.present();

      return false;
    }
  }

  // Leave the view
  leave() {
    this.navCtrl.pop();
  }
Run Code Online (Sandbox Code Playgroud)

Gab*_*eto -1

您不需要为此做出承诺,您只需要在用户能够离开页面时返回 true 或 false,因此,如果他想离开并在警报中确认这一点,您将其设置为allowedToLeavetrue 并弹出您的页面,它会ionViewCanLeave再次调用,但这次它不会输入您的 if 语句。

  // About to leave
  ionViewCanLeave() {
    this.api.getDefaultMedia().pause();

    if(!this.allowedToLeave) {
      let confirm = this.alertCtrl.create({
        title: 'Are you sure?',
        message: 'If you leave a class you will need to start over.  Are you sure you want to leave?  If you need a break you can pause by tapping the video.',
        buttons: [{
          text: 'OK',
          handler: () => {
            this.allowedToLeave = true;
            this.navCtrl.pop();
          },
        }, {
          text: 'Cancel',
          role: 'cancel'
        }],
      });
      confirm.present();
    };
    return true;
  }
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助。