Angular路由守卫 canDeactivate

目的

离开页面时,做出逻辑判断
以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;

示例代码

示例代码

参考资料

feat(abc: reuse-tab): new reuse-tab component plans!

拓展阅读

Angular路由守卫

原文地址:https://www.cnblogs.com/Lulus/p/9497870.html