Angular,使用 AuthGuard 的子路由
Angular, child routing with AuthGuard
我正在尝试将子路由与 AuthGaurd 结合使用。
一切似乎都很好:
a) 授权保护:
canLoad(route: Route): Observable<boolean> {
return this.authStore.select(selectAuthStatus).pipe(map(response => {
if (response) {
return true;
} else {
this.router.navigate(['/login']);
}
}));
}
它运行良好。
b) 每个模块都有子路由:
const routes = [
{
path : '',
component: SampleComponent
}
];
@NgModule({
declarations: [
SampleComponent
],
imports : [
RouterModule.forChild(routes),
...
c) 主路由:
const appRoutes: Routes = [
{ path: 'main', loadChildren: () => import('./main/sample/sample.module').then(m => m.SampleModule) },
{ path: '', loadChildren: () => import('./main/welcome-board/welcome-board.module').then(m => m.WelcomeBoardModule), canLoad: [AuthGuard] },
{
path : '**',
redirectTo: 'login'
}
];
d) 模板中的路由,通过变量:
[routerLink]="[item.url]"
路径有效,但一直在加载。
你应该使用 canActivate 而不是 canLoad:
canActivate(): boolean {
this.authStore.pipe(select(selectAuthStatus), take(1)).subscribe(response => {
this.selectorResponse = response;
});
if (this.selectorResponse) {
return true;
} else {
this.router.navigate(['/login']);
return false;
}
}
我正在尝试将子路由与 AuthGaurd 结合使用。
一切似乎都很好:
a) 授权保护:
canLoad(route: Route): Observable<boolean> {
return this.authStore.select(selectAuthStatus).pipe(map(response => {
if (response) {
return true;
} else {
this.router.navigate(['/login']);
}
}));
}
它运行良好。
b) 每个模块都有子路由:
const routes = [
{
path : '',
component: SampleComponent
}
];
@NgModule({
declarations: [
SampleComponent
],
imports : [
RouterModule.forChild(routes),
...
c) 主路由:
const appRoutes: Routes = [
{ path: 'main', loadChildren: () => import('./main/sample/sample.module').then(m => m.SampleModule) },
{ path: '', loadChildren: () => import('./main/welcome-board/welcome-board.module').then(m => m.WelcomeBoardModule), canLoad: [AuthGuard] },
{
path : '**',
redirectTo: 'login'
}
];
d) 模板中的路由,通过变量:
[routerLink]="[item.url]"
路径有效,但一直在加载。
你应该使用 canActivate 而不是 canLoad:
canActivate(): boolean {
this.authStore.pipe(select(selectAuthStatus), take(1)).subscribe(response => {
this.selectorResponse = response;
});
if (this.selectorResponse) {
return true;
} else {
this.router.navigate(['/login']);
return false;
}
}