我希望有2个具有相同路由的组件(根“ /”),但仅根据用户角色(来宾或已验证)加载一个组件。因此,Guest的主页和Authenticated的主页具有相同的路径。
我尝试为Guest创建一个防护,并为Authenticated用户创建一个防护,并在Routes数组的组件中应用每个防护,如下所示:
export const AppRoutes: Routes = [
{
path: '',
component: GuestLayoutComponent,
canActivate: [GuestGuard],
children: [
{
path: '',
loadChildren: './guest-components/guest.module#GuestModule',
}
],
},
{
path: '',
component: AuthLayoutComponent,
canActivate: [AuthGuard],
children: [
{
path: '',
loadChildren: './auth-components/auth.module#AuthModule',
}
],
},
{
path: '**',
component: ErrComponent,
},
];
但是它创建了一个无限循环。
还共享:
访客路线:
export const GuestRoutes: Routes = [
{
path: '',
children: [
{
path: '',
component: GuestHomeComponent,
}, {
path: 'about-guest',
component: GuestAboutComponent,
pathMatch: 'full'
},
]
}
];
AuthRoutes:
export const AuthRoutes: Routes = [
{
path: '',
children: [
{
path: '',
component: AuthHomeComponent,
}, {
path: 'about',
component: AuthAboutComponent,
pathMatch: 'full'
},
]
}
AuthGuard:
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}
canActivate(route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
return this.authService.isAuthenticated()
.then(
(authenticated: boolean) => {
if (authenticated) {
return true;
} else {
this.router.navigate(['/']);
return false;
}
}
);
}
}
GuestGuard:
export class GuestGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}
canActivate(route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
return this.authService.isAuthenticated()
.then(
(authenticated: boolean) => {
if (authenticated) {
this.router.navigate(['/']);
return false;
} else {
return true;
}
}
);
}
}
请找到link to the demo。
我该如何实现?我将不胜感激。
答案 0 :(得分:1)
我认为不可能有2个组件具有完全相同的路径。我不记得以前曾见过解决方案。
我不确定您为什么要实现这一目标,但是希望以下方法可以为您提供帮助。创建一个称为ContainerHomeComponent的父组件,将其指向您的路线。在.ts文件中,您查询“ this.authService.isAuthenticated()”以查找用户是否已通过身份验证,并分配给名为“ authenticated”的属性。在模板中,您所拥有的是:
$qs = [
'a' => 'a',
'quot;' => 'bar foo',
];
echo '<a href="?' . http_build_query($qs, null, '&', PHP_QUERY_RFC3986) . '">Link</a>';