Angular canActivate guard 如何从父路由重定向到子路由?
How to redirect from parent route to child route in Angular canActivate guard?
我有这条路线
AppRouting
{
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');
}
浏览器疯了:(
我应该使用什么路径?
这样;
canActivate()
return this.router.parseUrl('/user/check');
}
出现无限循环。
因为当您从 canActivate
return UrlTree
(由 this.router.parseUrl
编辑 return)当前导航被取消并开始新导航.
由于新导航将转到当前导航的子 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
运行s 两次。一个用于父导航,一个用于子导航。如果没有 if 条件,父导航将 运行 无限期地。
希望对您有所帮助。
我有这条路线
AppRouting
{
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');
}
浏览器疯了:(
我应该使用什么路径?
这样;
canActivate()
return this.router.parseUrl('/user/check');
}
出现无限循环。
因为当您从 canActivate
return UrlTree
(由 this.router.parseUrl
编辑 return)当前导航被取消并开始新导航.
由于新导航将转到当前导航的子 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
运行s 两次。一个用于父导航,一个用于子导航。如果没有 if 条件,父导航将 运行 无限期地。
希望对您有所帮助。