3

在我的 Ionic 5 应用程序中,我有以下导航路径。

PageHome -> PageA ->  PageB

我已经为 PageA 实现了 CanDeactivate 保护。

export class LeavePageGuard implements CanDeactivate<isDeactivatable>{
  canDeactivate(
    component: isDeactivatable
  ): Observable<boolean> | Promise<boolean> | boolean {
    return component.canPageLeave();
  }
}

当用户在保存之前编辑某些内容并按下后退按钮时,我会弹出一个弹出窗口以确认用户是否要离开。

  async canPageLeave() {

    if (this.byPassNav) {
      this.byPassNav = false;
      return true;
    }
    if (JSON.stringify(this.dataOld) != JSON.stringify(this.data)) {

      const alert = await this.alertCtrl.create({
        header: 'Unsaved Chnages',
        message: 'Do you want to leave?',
        buttons: [
          {
            text: 'No',
            role: 'cancel',
            handler: () => { }
          },
          {
            text: 'Yes'),
            role: 'goBack',
            handler: () => { }
          }
        ]
      });
      await alert.present();
      let data = await alert.onDidDismiss();
      if (data.role == 'goBack') {
        return true;
      } else {
        return false;
      }
    } else {
      return true;
    }
  }

为了继续前进,PageB我正在使用boolean byPassNav. 我在前进之前将此值设置为 TRUE 并且方法canPageLeave正在返回TRUE

除以下情况外,前向导航在一种情况下不起作用。

on PageA change some data and click on back button -> Confirmation pop up will open -> Select No -> Confirmation pop up will close and the same page remains open. Select button to move forward to PageB.

这会将导航移动到pageB但也会使页面成为根页面并删除所有路由历史记录。PageB在这个流程之后我无法回头。

编辑:添加代码isDeactivatable

export interface isDeactivatable {
    canPageLeave: () => Observable<boolean> | Promise<boolean> | boolean;
}
4

2 回答 2

4

似乎您只想canDeactivate在向后导航时执行警卫,而不是在向前导航时执行警卫。

如果是这种情况,请看一下这个有效的 Stackblitz 演示

演示

您可以避免使用byPassNav(这样您就不需要手动更新其值)并通过以下方式稍微更新您的警卫:

import { Injectable } from "@angular/core";
import { ActivatedRouteSnapshot, CanDeactivate, RouterStateSnapshot } from "@angular/router";
import { Observable } from "rxjs";

export interface isDeactivatable {
  canPageLeave: (
    nextUrl?: string // <--- here!
  ) => Observable<boolean> | Promise<boolean> | boolean;
}

@Injectable()
export class CanLeavePageGuard implements CanDeactivate<isDeactivatable> {
  canDeactivate(
    component: isDeactivatable,
    currentRoute: ActivatedRouteSnapshot,
    currentState: RouterStateSnapshot,
    nextState: RouterStateSnapshot
  ): Observable<boolean> | Promise<boolean> | boolean {
    return component.canPageLeave(nextState.url); // <--- and here!
  }
}

请注意,唯一的变化是该canLeave()方法现在将获取用户尝试导航到的下一页的 url。

通过这个小改动,您可以使用下一页的 url 来决定用户是否应该看到警报提示:

async canPageLeave(nextUrl?: string) {
    if (this.status === "saved") {
      return true;
    }

    if (nextUrl && !nextUrl.includes("home")) {
      return true;
    }

    const alert = await this.alertCtrl.create({
      header: "Unsaved Chnages",
      message: "Do you want to leave?",
      buttons: [
        {
          text: "No",
          role: "cancel",
          handler: () => {}
        },
        {
          text: "Yes",
          role: "goBack",
          handler: () => {}
        }
      ]
    });

    await alert.present();

    const data = await alert.onDidDismiss();

    if (data.role == "goBack") {
      return true;
    } else {
      return false;
    }
  }

还有另一种“替代”方法,涉及从NavController.

这种方法更像是一种解决方法,因为导航方向实际上是 的私有属性NavigationController,但如果我们愿意,我们仍然可以访问它:

async canPageLeave() {
    if (this.status === "saved") {
      return true;
    }   

    // ----------------------
    // Alternative approach
    // ----------------------
    // The direction is a private property from the NavController
    // but we can still use it to see if the user is going back
    // to HomePage or going forward to SecondPage.
    // ----------------------

    const { direction } = (this.navCtrl as unknown) as {
      direction: "forward" | "back" | "root";
    };

    if (direction !== "back") {
      return true;
    }

    const alert = await this.alertCtrl.create({
      header: "Unsaved Chnages",
      message: "Do you want to leave?",
      buttons: [
        {
          text: "No",
          role: "cancel",
          handler: () => {}
        },
        {
          text: "Yes",
          role: "goBack",
          handler: () => {}
        }
      ]
    });

    await alert.present();

    const data = await alert.onDidDismiss();

    if (data.role == "goBack") {
      return true;
    } else {
      return false;
    }
  }

这种方法可能听起来更简单,因为您不需要手动检查下一个 url,但请记住,Ionic 团队将来可能会在没有任何通知的情况下将其删除(因为它是私有财产)所以最好只使用nextUrl类似上面解释的。

于 2021-02-27T10:28:47.943 回答
0

“一个类可以实现的接口,作为决定是否可以停用路线的守卫。如果所有守卫返回 true,则导航继续。如果任何守卫返回 false,则取消导航。如果任何守卫返回 UrlTree,则取消当前导航并一个新的导航开始到从守卫返回的 UrlTree。” [源]

在这种守卫中,没有随机行为,这完全取决于您的守卫返回什么!如果你的一个守卫返回一个 UrlTree,这个将覆盖旧的!我认为这是你的情况!

isDeactivatable是一个组件吗?可以请添加完整的代码!您要设置警卫的组件,...

于 2020-10-31T11:55:48.600 回答