简体   繁体   中英

Angular guards for navigating to a parent route

I've got an application with the following routes:

  • /root/foo
  • /root/bar
  • /root/foo/(outlet:X)
  • /root/bar/(outlet:X)

Navigating to /root/foo or /root/bar will compute a value X and redirect to /root/foo/(outlet:X) or /root/bar/(outlet:X) respectively.

Is there a way to implement a Guard such that clicking a router link to /root/foo from /root/foo/(outlet:X) will be prevented?

您可以实现canDeactivate保护,检查当前和目标URL,并在特定情况下阻止导航。

I managed to get it working by using a CanDeactivate guard, but on the child components.

Route example: { path: 'root/foo', component: ListComponent, children: [ { path: ':id', canDeactivate: [CanNavigateToParentRouteGuard], component: ChildComponent, outlet: 'outlet' } ] }, Guard: canDeactivate(component: ChildComponent, currentRoute: ActivatedRouteSnapshot, currentState: RouterStateSnapshot, nextState?: RouterStateSnapshot): boolean { return !currentState.url.startsWith(nextState.url); } canDeactivate(component: ChildComponent, currentRoute: ActivatedRouteSnapshot, currentState: RouterStateSnapshot, nextState?: RouterStateSnapshot): boolean { return !currentState.url.startsWith(nextState.url); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM