Angular 6 TypeError:guard不是函数

问题描述 投票:1回答:1

我正在尝试实施一个简单的警卫:

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,
]

但我得到这个错误,我不明白为什么?

javascript angular typescript module routing
1个回答
7
投票

AuthGuard本质上是一项服务,应该注册到您的AppModule。将AuthGuard添加到providers中的app.module.ts数组中。

编辑:下面的每个对话,问题来自于当AuthGuard实现canActivateChild时在路线中使用CanActivate

© www.soinside.com 2019 - 2024. All rights reserved.