我正在尝试实施一个简单的警卫:
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,
]
但我得到这个错误,我不明白为什么?
AuthGuard
本质上是一项服务,应该注册到您的AppModule。将AuthGuard
添加到providers
中的app.module.ts
数组中。
编辑:下面的每个对话,问题来自于当AuthGuard实现canActivateChild
时在路线中使用CanActivate
。