Search code examples
angularangular-routingauth-guard

Angular 6 : Empty path bypass auth guard


I'm trying to use the Angular router, and I'm having an issue on the empty path . Here's my routes:

const routes: Routes = [

    { path: 'feed', loadChildren: './feed/feed.module#FeedModule', canLoad: [AuthGuardService] },
    { path: 'login', component: LoginPage },
    { path: 'register', component: RegisterPage },
    { path: '', redirectTo: '/feed', pathMatch: 'full' },
    { path: '**', redirectTo: '/' }
];

My AuthGuardService has a method canLoad which always returns false and redirects to the '/login' path :

...
@Injectable()
export class AuthGuardService implements CanLoad {
  constructor(private router: Router) {
  }
  canLoad(route: Route): boolean {

    this.router.navigate([ '/login' ]);
    return false;
  }
}

When I go to 'localhost:4200/feed', I'm redirected to '/login'.

But if I go to 'localhost:4200/', the auth guard is ignored and the components of my feed module are displayed.

Do you have any idea why ?

Thanks !


Solution

  • I've solved my issue, sorry for the delay : I needed to use a component and to use canActivate in order to load the child module

    {
        path: 'feed',
        canActivate: [ AuthGuard ],
        component: FeedComponent,
        children: [
            {
          path: '',
          loadChildren: () => FeedModule
    }]}
    

    Lazy loading for children works as well !

    Cheers !