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

后端 未结 12 2110
陌清茗
陌清茗 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条回答
  •  走了就别回头了
    2021-02-03 20:27

    Since you got the solution as it was due to syntax issue. I just wanted to share this info.

    we need to provide the AuthGaudSerivce as provider in only that module that correspond to respective route. No need to provide in main module or root module as main module will automatically load all the given sub module.This helps in keeping the code modular and encapsulated.

    for example, suppose we have below scenario

    1. we have module m1
    2. we have route m1r in module m1
    3. route m1r has 2 route r1 and r2
    4. we want to protect r1 using authGaurd
    5. finally we have main module that is dependent on sub module m1 
    

    Below is just prototype, not the actual code for understanding purpose

    //m1.ts    
    import {AuthGaurd} from './auth.gaurd.service'
    import {m1r} from './m1r'
        @NgModule(
         imports: [m1r],
         providers: [AuthGaurd]
        )
        export class m1{
        }
    
    //m1r.ts
    import {AuthGaurd} from './auth.gaurd.service'
    const authRoute = [
     {path: '/r1', component: 'authComponent', canActivate: [AuthGaurd]},
     {path: '/r2', component: 'other'}
    ]
    export authRoute
    
    //main.module.ts
    import {m1} from ''
    import {mainComponent} from ''
    @NgModule({
      imports: [m1],
      bootstrap: [mainComponent]
      })
    export class MainModule{}    
    

提交回复
热议问题