Angular路由守卫 canDeactivate (ng-zorro)

本文介绍如何在ng-alain框架中实现页面离开前的数据保存提示,通过自定义CanDeactivateGuardService来拦截页面导航,确保数据完整性和用户体验。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原文出处:http://www.cnblogs.com/Lulus/p/9497870.html

目的

离开页面时,做出逻辑判断
以ng-alain的项目为基础做演示
效果如图:
test3

关键代码

定义一个CanDeactivateGuardService

export class CanDeactivateGuardService implements CanDeactivate<CanDeactivateComponent> {

    canDeactivate(component: CanDeactivateComponent,
                  route: ActivatedRouteSnapshot,
                  state: RouterStateSnapshot): Observable<boolean> | boolean {
        return component.leaveTip();
    }
}

在component中完成leaveTip方法

leaveTip() {
  return Observable.create((observer) => {
    if(!this.isSave){
      this.modalService.confirm({
        nzTitle: '页面离开提示',
        nzContent: '数据尚未保存,是否离开该页面?',
        nzOnOk: async () => {
            observer.next(true);
        },
        nzOnCancel: () => {
            observer.next(false);
        }
      });
    }
    else{
      observer.next(true);
    }
  });
}

设置ng-alain的ReuseTabMatchMode,排除can-deactivate这个目标路由

this.reuseTabService.mode = ReuseTabMatchMode.URL;
const excludes = new Array<RegExp>();
excludes.push(new RegExp('/can-deactivate'));
this.reuseTabService.excludes = excludes;

示例代码

https://github.com/zLulus/NotePractice/tree/dev3/Website/DotNetCore/CoreNgAlain/src/app/routes/can-deactivate

参考资料

https://github.com/cipchk/ng-alain/issues/101

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值