如何从 child 导航到 parent 的同级?
How can I navigate to parent's sibling from child?
我正在尝试将未经授权的用户从其他路径重定向到主页。我在 app-routing.module 中的路线如下所示:
const routes: Routes = [
{
path: '',
component: MainPageComponent,
canActivate: [MainPageAuthGuard],
},
{
path: 'dashboard',
component: DashboardComponent,
canActivate: [AuthGuard],
children: [
{
path: '',
component: RootComponent,
},
{
path: 'profile',
component: ProfileComponent,
},
{
path: 'settings',
component: SettingsComponent,
},
]
},
];
如您所见,我有一个 AuthGuard
供我使用,代码如下:
export class AuthGuard implements CanActivate {
constructor(
private router: Router,
private authService: AuthService,
) {
}
public canActivate(route: ActivatedRouteSnapshot): boolean {
if (!this.authService.isAuthorized) {
this.router.navigate(['']);
return false;
}
return true;
}
}
事情是:
当我在路线 '/dashboard/settings' 上注销时 - 我被重定向到 '/dashboard'
当我在路线 '/dashboard' 上注销时 - 我被重定向到 home 页面
而且我已经尝试过许多不同的导航方式,甚至(只是为了检查)window.open() 的工作方式相同:在“/dashboard”中正常工作,而不是在 [=38= 中工作]
因此,解决方案是用 canActivateChild 守卫替换 canActivate 守卫。
'/dashboard' 路线现在看起来像这样:
path: 'dashboard',
component: DashboardComponent,
canActivateChild: [AuthGuard],
和 AuthGuard:
export class AuthGuard implements CanActivateChild {
constructor(
private router: Router,
private authService: AuthService,
) {
}
public canActivateChild(childRoute: ActivatedRouteSnapshot,
state: RouterStateSnapshot): boolean {
if (!this.authService.isAuthorized) {
this.router.navigateByUrl('');
return false;
}
return true;
}
}
我正在尝试将未经授权的用户从其他路径重定向到主页。我在 app-routing.module 中的路线如下所示:
const routes: Routes = [
{
path: '',
component: MainPageComponent,
canActivate: [MainPageAuthGuard],
},
{
path: 'dashboard',
component: DashboardComponent,
canActivate: [AuthGuard],
children: [
{
path: '',
component: RootComponent,
},
{
path: 'profile',
component: ProfileComponent,
},
{
path: 'settings',
component: SettingsComponent,
},
]
},
];
如您所见,我有一个 AuthGuard
供我使用,代码如下:
export class AuthGuard implements CanActivate {
constructor(
private router: Router,
private authService: AuthService,
) {
}
public canActivate(route: ActivatedRouteSnapshot): boolean {
if (!this.authService.isAuthorized) {
this.router.navigate(['']);
return false;
}
return true;
}
}
事情是:
当我在路线 '/dashboard/settings' 上注销时 - 我被重定向到 '/dashboard'
当我在路线 '/dashboard' 上注销时 - 我被重定向到 home 页面
而且我已经尝试过许多不同的导航方式,甚至(只是为了检查)window.open() 的工作方式相同:在“/dashboard”中正常工作,而不是在 [=38= 中工作]
因此,解决方案是用 canActivateChild 守卫替换 canActivate 守卫。
'/dashboard' 路线现在看起来像这样:
path: 'dashboard',
component: DashboardComponent,
canActivateChild: [AuthGuard],
和 AuthGuard:
export class AuthGuard implements CanActivateChild {
constructor(
private router: Router,
private authService: AuthService,
) {
}
public canActivateChild(childRoute: ActivatedRouteSnapshot,
state: RouterStateSnapshot): boolean {
if (!this.authService.isAuthorized) {
this.router.navigateByUrl('');
return false;
}
return true;
}
}