Can't resolve all parameters for AuthGuard
Asked Answered
A

1

6

I have this 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;
  }
}

And I have provided it in my AppModule:

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

And i tried to use this guard in my routing module like this:

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 {
}

And I get this error:

enter image description here

Did I miss something? Where is the source of this error?

EDIT: I am using Angular 4.4.6

It work fine when I use the basic route guard, and updated the route configurations:

@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']}
    ]
  }
];

**My 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"
    ]
  }
}
Amnesty answered 16/11, 2017 at 13:50 Comment(3)
Can you post your tsconfig.json?Holly
Okey, I have upadated my post.Amnesty
Are you sure there is @Injectable before export class AuthGuard implements CanActivate ?European
E
13

You just missed to put @Injectable() before your AuthGuard service

European answered 16/11, 2017 at 14:23 Comment(1)
I have completely forgot this. Thank you!Amnesty

© 2022 - 2024 — McMap. All rights reserved.