无法解析AuthGuard的所有参数

时间:2017-11-16 13:50:19

标签: angular angular-router-guards canactivate angular-guards

我有AuthGuard

export class AuthGuard implements CanActivate {

  constructor (private router: Router) {}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    if (localStorage.getItem('token')) {
      return true;
    }

    this.router.navigate(['/login']);
    return false;
  }
}

我已经在我的AppModule

中提供了它
@NgModule({
  declarations: [/*...*/],
  imports: [NotificationRoutingModule],
  providers: [AuthService, AuthGuard],
  bootstrap: [AppComponent]
})
export class AppModule {
}

我试图在我的路由模块中使用这个后卫:

const routes = [
  {
    path: 'notification',
    component: NotificationRootComponent
    children: [
      {path: '', redirectTo: 'list', pathMatch: 'full'},
      {path: 'list', component: NotificationListComponent, canActivate: [AuthGuard]},
      {path: ':id', component: NotificationDetailComponent, canActivate: [AuthGuard]}
    ]
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
  declarations: []
})
export class NotificationRoutingModule {
}

我收到了这个错误:

enter image description here

我错过了什么吗?这个错误的来源在哪里?

修改 我使用的是Angular 4.4.6

当我使用基本路线防护并且更新路线配置时,它工作正常:

@NgModule({
  declarations: [],
  imports: [],
  providers: [
    {
      provide: 'CannotBeActivated',
      useValue: () => {
        return false;
      }
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {
}


const routes = [
  {
    path: 'notification',
    component: NotificationRootComponent,
    children: [
      {path: '', redirectTo: 'list', pathMatch: 'full'},
      {path: 'list', component: NotificationListComponent, canActivate: ['CannotBeActivated']},
      {path: ':id', component: NotificationDetailComponent, canActivate: ['CannotBeActivated']}
    ]
  }
];

**我的tsconfig.json:**

{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2017",
      "dom"
    ]
  }
}

1 个答案:

答案 0 :(得分:7)

您错过了在AuthGuard服务之前放置@Injectable()