我在我的地图上加了一条有警卫的路线
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;
}