Search code examples
angulartypescriptangular-routing

Angular, child routing with AuthGuard


I am trying to using child routing with AuthGaurd.

Everything seems to be good:

a) AuthGuard:

canLoad(route: Route): Observable<boolean> {

  return this.authStore.select(selectAuthStatus).pipe(map(response => {
    if (response) {
      return true;
    } else {
      this.router.navigate(['/login']);
    }
  }));
}

And it is working perfectly.

b) Each module has child routing:

    const routes = [
        {
            path     : '',
            component: SampleComponent
        }
    ];

@NgModule({
    declarations: [
        SampleComponent
    ],
    imports     : [
        RouterModule.forChild(routes),
...

c) main routing:

const appRoutes: Routes = [
    { path: 'main', loadChildren: () => import('./main/sample/sample.module').then(m => m.SampleModule) },
    { path: '', loadChildren: () => import('./main/welcome-board/welcome-board.module').then(m => m.WelcomeBoardModule), canLoad: [AuthGuard] },
    {
        path      : '**',
        redirectTo: 'login'
    }
];

d) routing in template, via variable:

[routerLink]="[item.url]"

The path is valid, but it is constantly loading.


Solution

  • You should use canActivate instead of canLoad:

    canActivate(): boolean {
        this.authStore.pipe(select(selectAuthStatus), take(1)).subscribe(response => {
            this.selectorResponse = response;
        });
    
        if (this.selectorResponse) {
            return true;
        } else {
            this.router.navigate(['/login']);
            return false;
        }
    }