angular - Ionic 5 中 CanDeactivate 守卫的导航问题

标签 angular ionic-framework routes ionic5 candeactivate

在我的 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;
}

最佳答案

似乎您只想在向后导航时执行 canDeactivate 守卫,但在向前导航时不执行。

如果是这样,请查看 this working Stackblitz demo :

demo

你可以避免使用 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 的一个private 属性,但如果需要,我们仍然可以访问它:

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 团队将来可能会在没有任何通知的情况下将其删除(因为它是私有(private)属性(property)),因此它可能会更好像上面解释的那样使用 nextUrl

关于angular - Ionic 5 中 CanDeactivate 守卫的导航问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64270332/

相关文章:

angular - ngrx - 有条件地停止/删除效果/ Action

angular - 无法获取 CanActivate 守卫中惰性模块的路由参数

javascript - Angular 2在初始化第二张 map 时无法读取未定义的属性 'maps'

ios - 如何通过使用 Ionic2 在 iPhone/iPad 上点击返回键转到下一个输入?

asp.net-mvc - 堆栈溢出问题路由

php - Laravel 5.1 - 获取当前路线

angular - environment.ts 文件通常是提交还是忽略?

reactjs - Uncaught ReferenceError : process is not defined (yes I tried all the solutions internet says should solve this)

ionic-framework - 在 Windows 10 上安装 ionic 和 cordova

asp.net-mvc-3 - 在 ASP.NET MVC 中映射自定义路由