Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't resolve all parameters for AuthGuard

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"
    ]
  }
}
like image 550
Laiso Avatar asked Nov 16 '17 13:11

Laiso


1 Answers

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

like image 193
Faly Avatar answered Oct 09 '22 01:10

Faly