“No provider for AuthGuard!” using CanActivate in Angular 2

后端 未结 12 2086
陌清茗
陌清茗 2021-02-03 20:09

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

12条回答
  •  梦毁少年i
    2021-02-03 20:37

    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.

提交回复
热议问题