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路由守衛


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM