代码之家  ›  专栏  ›  技术社区  ›  Gargoyle

Angular的route guard未在应用程序内运行

  •  0
  • Gargoyle  · 技术社区  · 5 年前

    我在我的地图上加了一条有警卫的路线 app-routing.module.ts

    {path: 'detail/:id', component: DetailComponent, canDeactivate: [PendingChangesGuard]},
    

    如果我试图完全离开angular应用程序,那么我会看到从 PendingChangesGuard . 但是,如果我单击angular应用程序中的任何其他路由,则不会执行路由保护。在这种情况下,如何使其运行?

    export interface ComponentCanDeactivate {
        canDeactivate: () => boolean;
    }
    
    @Injectable({
        providedIn: 'root'
    })
    export class PendingChangesGuard implements CanDeactivate<ComponentCanDeactivate> {
        canDeactivate(component: ComponentCanDeactivate, currentRoute: ActivatedRouteSnapshot, currentState: RouterStateSnapshot, nextState?: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
            return component.canDeactivate ? true : confirm('WARNING: You have unsaved changes. Press Cancel to go back and save your changes.');
        }
    }
    

    DetailComponent 我这样做:

    @HostListener('window:beforeunload')
    canDeactivate(): boolean {
        console.info("I got called");
        return !this.formGroup.dirty;
    }
    
    1 回复  |  直到 5 年前
        1
  •  0
  •   Simon K    5 年前

    你不是在打电话吗 component.canDeactivate 小心点。您基本上是检查它是否已定义(始终为真),然后返回 true .

    更新至:

    export class PendingChangesGuard implements CanDeactivate<ComponentCanDeactivate> {
        canDeactivate(component: ComponentCanDeactivate, currentRoute: ActivatedRouteSnapshot, currentState: RouterStateSnapshot, nextState?: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
            return component.canDeactivate() ? true : confirm('WARNING: You have unsaved changes. Press Cancel to go back and save your changes.');
        }
    }