"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.