2

我有这条路线

应用路由

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

用户路由

{
    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
          )
      }
    ]
  }

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

canActivate() 
    return this.router.parseUrl('/user/check');
  }

浏览器疯了:(

我应该使用什么路径?

4

1 回答 1

5

这样;

canActivate() 
    return this.router.parseUrl('/user/check');
}

发生无限循环。

因为当您从当前导航返回一个UrlTree(由返回)时,会取消并开始一个新的导航。this.router.parseUrlcanActivate

由于新导航将转到当前导航的子 url(子 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');
}

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

我希望它有所帮助。

于 2020-05-19T22:42:37.453 回答