我只想实现一个简单的守卫:
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.模块中:
providers: [
AuthGuard,
],
在app.module中:
imports: [
AuthModule,
]
但是我犯了这个错误,我不知道为什么?
最佳答案
AuthGuard
本质上是一种服务,应该注册到您的AppMead中。将AuthGuard
添加到providers
中的app.module.ts
数组。
编辑:根据下面的对话,问题来自authguard实现canActivateChild
时在路由中使用CanActivate
。
关于javascript - Angular 6 TypeError:Guard不是函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52389014/