1. 程式人生 > >Angular路由守衛 canDeactivate (ng-zorro)

Angular路由守衛 canDeactivate (ng-zorro)

原文出處: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