【问题标题】:How to redirect from parent route to child route in Angular canActivate guard?如何在Angular canActivate保护中从父路由重定向到子路由?
【发布时间】:2020-05-20 06:48:01
【问题描述】:

我有这条路线

应用路由

{
   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');
  }

浏览器疯了:(

我应该使用什么路径?

【问题讨论】:

    标签: angular angular-routing angular-guards


    【解决方案1】:

    这样;

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

    发生无限循环。

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

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

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

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 2020-02-26
      • 2017-08-10
      • 2015-05-02
      • 2017-08-21
      • 2021-08-28
      • 1970-01-01
      • 2018-10-22
      • 1970-01-01
      • 2022-06-15
      相关资源
      最近更新 更多