0

I got problem with routing inside lazy loaded modules.

Here is my "root" routes:

const routes: Routes = [
  {path: '', redirectTo: 'admin', pathMatch: 'full' },
    {path: 'admin', loadChildren: 'app/admin.module#AdminModule'}
];

@NgModule({
  imports: [
      RouterModule.forRoot(routes)
  ],
  exports: [
      RouterModule
  ]
})
export class MainRoutingModule {}

So what I expect from my app, is to redirect empty path to /admin - this works fine, module is loaded.

in AdminModule I got another redirect:

const routes: Routes = [
    {path: '', component: AdminComponent, children: [
        {path: '', redirectTo: 'app', pathMatch: 'full' },
        {path: 'app', loadChildren: './app/app.module#AppModule', canActivate: [ AuthGuard ] },
        {path: 'login', component: LoginComponent}
    ]},
];

@NgModule({
    imports: [
        RouterModule.forChild(routes),
        AppModule
    ],
    exports: [
        RouterModule
    ]
})
export class AdminRoutingModule {}

Here I got two scenarios:

  • if user is authenticated redirect to app - so the whole path would be /admin/app
  • otherwise redirect to login - so the whole path should be /admin/login

and finally routing in admin application:

const routes: Routes = [
  { path: '', component: AppComponent, children: [
    { path: '',  redirectTo: 'home', pathMatch: 'full' },
    { path: 'home', component: HomeComponent},
  ]}
];

And now problems starts. If I will enter my side with url localhost:3000/admin/app/(*) everything works as expected, AuthGuard is invoked, url is ok, in case that user is unauthenticated he gets redirect to login page.

But!: If I will enter localhost:3000 app redirects me to localhost:3000/admin/home (app is missing) and AuthGuard is not invoked. It looks like Angular is ommiting the admin-routing.module and goes directly to the last one.

What is the reason? How can I fix that?

Maciej Treder
  • 11,866
  • 5
  • 51
  • 74

1 Answers1

0

in AdminModule You add canActivate in the default route .

const routes: Routes = [
    {path: '', component: AdminComponent, children: [
        {path: '', redirectTo: 'app', pathMatch: 'full'  canActivate: [ AuthGuard ]},
        {path: 'app', loadChildren: './app/app.module#AppModule', canActivate: [ AuthGuard ] },
        {path: 'login', component: LoginComponent}
    ]},
];
suvankar bose
  • 291
  • 2
  • 12