我正试图实现一个简单的保护措施:
export class AuthGuard implements CanActivate {
constructor(private router: Router) {
}
canActivate(
route: ActivatedRouteSnapshot,
_state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
console.log('guarded ?!?');
return true;
}
并在我的应用程序路由模块中使用它:
const appRoutes: Routes = [
{
path: '',
canActivateChild: [AuthGuard],
children: [
{
path: 'auth',
component: UnauthenticatedContainerComponent,
data: { excludeLogin: true },
children: [
{ path: 'login', component: LoginComponent },
],
},
{
path: '',
component: AuthenticatedContainerComponent,
data: { requireLogin: true },
children: [
{
path: '',
component: RequestContainerComponent,
children: [
{ path: 'list', component: RequestListComponent },
{ path: 'results/:id', component: RequestResultListComponent},
],
},
],
},
],
},
{ path: '**', redirectTo: '/' },
];
@NgModule({
imports: [
RouterModule.forRoot(appRoutes, {
enableTracing: false,
onSameUrlNavigation: 'reload',
}),
],
exports: [RouterModule],
})
export class AppRoutingModule {
}
在auth.module中:
providers: [
AuthGuard,
],
在app.module中:
imports: [
AuthModule,
]
但是我得到这个错误,我不知道为什么吗?
答案 0 :(得分:7)
AuthGuard
本质上是一项服务,应注册到您的AppModule中。将AuthGuard
添加到providers
中的app.module.ts
数组中。
编辑:下面的每次会话,问题出在AuthGuard实现canActivateChild
时在路由中使用CanActivate
。