"No provider for AuthGuard!" using CanActivate in Angular 2 "No provider for AuthGuard!" using CanActivate in Angular 2 angular angular

"No provider for AuthGuard!" using CanActivate in Angular 2


I had this same issue after going through the Route Guards section of Routing and Authorization tutorial on the Angular website https://angular.io/docs/ts/latest/guide/router.html, it is section 5.

I am adding AuthGuard to one of my main routes and not to child routes like the tutorial shows.

I fixed it by added AuthGuard to my list of providers in my app.module.ts file, so that file now looks like this:

import { AppComponent } from './app.component';import {AppRoutingModule} from './app-routing.module';import {AuthGuard} from './auth-gaurd.service';import { AnotherPageComponent } from './another-page/another-page.component';import { LoginPageComponent } from './login-page/login-page.component';@NgModule({  imports: [    BrowserModule,    FormsModule,    JsonpModule,    AppRoutingModule,    HttpModule  ],  declarations: [    AppComponent,    LoginPageComponent,    AnotherPageComponent  ],  providers: [AuthGuard],  bootstrap: [AppComponent]})export class AppModule { }

I have gone back through the tutorial and in their app.module.ts file, they do not add AuthGuard to the providers, not sure why.


Try to add

@Injectable({ providedIn: 'root'})no need to add to module provider.


Also, don't fall into the trap of using a literal for the guard class inside your routing configuration, just because some blog articles do:

{ path: 'whatever', component: WhatEverComponent, canActivate: ['WhatEverGuard'] }

is not going to work (No provider for...), instead, use the class directly:

{ path: 'whatever', component: WhatEverComponent, canActivate: [WhatEverGuard] }

Another hint, when lazy loading components, the guard is applied in the routing configuration of the parent component, not in the routing configuration of the lazy loaded component.