I'm working in an Angular 9 app and I'm trying to load (or not) an specific module only when my app state (ngrx) have a property != null
First, I have an AuthGuard in my routes but with canActivate. So I want the 'dashboard' module only loads when mt AppState have a token
Here is my route file
const routes: Routes = [
{
path: '',
component: AppLayoutComponent,
canActivate: [ AuthGuard ],
children: [
{ path: '', loadChildren: () => import('./pages/modules/dashboard/dashboard.module').then(m => m.DashboardModule) }
]
},
{
path: '',
component: AuthLayoutComponent,
children: [
{ path: 'session', loadChildren: () => import('./pages/modules/session/session.module').then(m => m.SessionModule) }
]
},
{
path: '**',
redirectTo: 'session/not-found'
}];
And this is my AuthGuard. It localestorage doesn't have a session, then redirects to the login page.
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private router: Router, public authService: AuthService) {}
public canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
if (localStorage.getItem('session')) {
// logged in so return true
return true;
}
// not logged in so redirect to login page with the return url
this.router.navigate(['session/signin']);
return false;
}
}
this is kind of what I want to do whit the canLoad in AuthModuleGuard, but this doesn't work
public canLoad(): Observable<boolean> {
return this.store.select('session').pipe(
take(1),
map((authstate) => {
console.log('Token status', authstate.token);
if (authstate.token !== null) {
return true;
} else {
this.router.navigate(['session/signin']);
return false;
}
})
);
}
if I do this... the application gives me errors and still loads both files
{
path: '',
component: AppLayoutComponent,
canLoad: [ AuthModuleGuard ],
children: [ ... ]
}
and If I do this ... the app never finish loading
{ path: '', canLoad: [ AuthModuleGuard ], loadChildren: () => import('./pages/modules/dashboard/dashboard.module').then(m => m.DashboardModule) },
HERE IS A STACKBLITZ EXAMPLE (including my folder structure)---> https://stackblitz.com/edit/angular-ivy-nasx7r
I need a way to load the dashboard module (and other modules) only if the token in my store are seted, and If is not, redirect to the Login. Please help