如何在Angular canActivate guard中从父路由重定向到子路由?

use*_*366 2 angular-routing angular angular-guards

我有这些路线

应用路由

{
   path: 'user',
   canLoad: [AuthGuard],
   loadChildren: () =>
   import('./user/user.module').then((m) => m.PublicUserModule)
}
Run Code Online (Sandbox Code Playgroud)

用户路由

{
    path: '',
    component: PublicUserPageComponent,
    canActivate: [UserPhonesCheckGuard],
    children: [
      /*{
        path: '',
        pathMatch: 'full',
        redirectTo: 'check'
      },*/
      {
        path: 'account',
        loadChildren: () =>
          import('./account/user-account.module').then(
            (m) => m.PublicUserAccountModule
          )
      },
      {
        path: 'check',
        loadChildren: () =>
          import('./check/user-check.module').then(
            (m) => m.PublicUserCheckModule
          )
      }
    ]
  }
Run Code Online (Sandbox Code Playgroud)

根据某些条件使用 UserPhonesCheckGuard 我想重定向或检查或帐户子路由,但使用

canActivate() 
    return this.router.parseUrl('/user/check');
  }
Run Code Online (Sandbox Code Playgroud)

浏览器发疯了:(

我应该使用什么路径?

ysf*_*ysf 5

通过这种方式;

canActivate() 
    return this.router.parseUrl('/user/check');
}
Run Code Online (Sandbox Code Playgroud)

发生无限循环。

因为当您从当前导航返回 a UrlTree(由 返回this.router.parseUrl)时,canActivate将取消并开始新的导航。

由于新导航将转到当前导航的子 url(子),因此canActivate守卫会再次为新导航运行,从而导致无限循环。

这就是为什么您需要一种方法来检测子导航canActivate并打破无限循环。检测子导航的一种方法是控制 url。如;

canActivate(next: ActivatedRouteSnapshot,state: RouterStateSnapshot) {
  console.log(state.url)

  if(state.url === "/user/check" || state.url === "/user/account") 
    return true;

  if(someCondition) /* here you determine which child to navigate */
    return this.router.parseUrl('/user/check');
  else
    return this.router.parseUrl('/user/account');
}
Run Code Online (Sandbox Code Playgroud)

我在这里创建了一个简单的演示。在演示中,您可以在canActivate每次导航运行两次的控制台中看到。一种用于父导航,一种用于子导航。如果没有 if 条件,父导航将无限期运行。

我希望它有帮助。