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

54,282

Solution 1

Actually, it was only a typo in an import...

I was typing

import { AuthGuard } from './../Authentification/auth.guard';

instead of

import { AuthGuard } from './../authentification/auth.guard';

making it not working but at the same time not displaying me any error...

(sadface)

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

Solution 3

Try to add

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

Solution 4

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.

Solution 5

For those who still have this error - don't forget to include your AuthGuard service or class to main bootstrap function. And don't forget to import this service before bootstrap runs.

import { bootstrap } from '@angular/platform-browser-dynamic';

import { AppComponent } from './app.component';
import { AuthGuard } from './shared/auth.service';

bootstrap(AppComponent, [
  appRouterProviders,
  AuthGuard
]);

Angular 2 team did not mention this in main router docs, and it took couple of hours for me to figure it out.

Share:
54,282
Alex Beugnet
Author by

Alex Beugnet

Just a french guy specialized in front-end development and especially JavaScript, and the Angular Framework.

Updated on July 09, 2022

Comments

  • Alex Beugnet
    Alex Beugnet almost 2 years

    EDIT : Obviously this is outdated, now you provide your guard at the providers array in an NgModule. Watch other answers or official documentation for more information.

    • bootstrapping on a component is outdated
    • provideRouter() is outdated as well


    I'm trying to setup Authentication in my project, using a login and AuthGuard from the Angular2 guide : https://angular.io/docs/ts/latest/guide/router.html

    I'm using the release : "@angular/router": "3.0.0-beta.1".

    I'll try to explain as much as possible, feel free to tell me if you need more details.


    I have my main.ts file which boostraps the app with the following code :

    bootstrap(MasterComponent, [
        APP_ROUTER_PROVIDERS,
        MenuService
    ])
    .catch(err => console.error(err));
    

    I load the MasterComponent, which loads a Header containing buttons that allow me to navigate through my app and it also contains my main for now.

    I'm following the guide to make my app work the same way, with the following app.routes.ts :

    export const routes: RouterConfig = [
        ...LoginRoutes,
        ...MasterRoutes
    ];
    
    export const APP_ROUTER_PROVIDERS = [
        provideRouter(routes),
        AUTH_PROVIDERS
    ];
    

    And the login.routes.ts from the guide, which defines my AuthGuard :

    export const LoginRoutes = [
        { path: 'login', component: LoginComponent }
    ];
    
    export const AUTH_PROVIDERS = [AuthGuard, AuthService];
    

    my Master component has its own route definition, which also contains the guard I'm trying to setup. master.routes.ts :

    export const MasterRoutes : RouterConfig = [
        { path: '', redirectTo: '/accueil', pathMatch: 'full' },
    
        {
            path: 'accueil',
            component: AccueilComponent
        },
    
        { path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] },
    ];
    

    And I'm using the same files as the guide, which are auth.guard.ts, auth.service.ts, login.component.ts and login.routes.ts.


    In my header.component.ts file, when I try to access any routes, it's working just fine, but when I try to access the guarded path (/dashboard), I get the No provider for AuthGuard! error.

    I saw the recent post with the same issue as mine (NoProviderError using CanActivate in Angular 2), but to me the guard is bootstraped correctly up to the main.ts file, so my router should know which routes should be provided with the AuthGuard right ?

    Any help or advice would be greatly appreciated. Thanks !