ahsan ayub
ahsan ayub

Reputation: 307

Angular lazy loaded module with child component default route

Angular 9. Child component is not loaded with lazy loaded module component. Here is my code.

app-routing.module.ts

  {
    path: '',
    redirectTo: '/auth',
    pathMatch: 'full'
  },
  {
    path: 'auth',
    loadChildren: () => import('./pages/auth/auth.module').then(m => m.AuthModule),
  }

auth.module.ts

  {
    path: '',
    component: AuthRootComponent,
    children: [
      { path: 'login', component: LoginComponent},
      { path: 'forgot', component: ForgotPasswordComponent},
      { path: '', redirectTo: 'login', pathMatch: 'full' },
    ]
  }

When i use localhost:4200/ it redirects me to localhose:4200/auth. It does not load login component.

But when i hit url in browser (localhost:4200/auth) it will load login component, and new url will be desired url which is localhost:4200/auth/login.

Please tell me, why it does not load login from child array when auth module is loaded and the url is localhost:4200? URL should be localhost:4200/auth/login but right now getting url localhost:4200/auth

Upvotes: 2

Views: 1828

Answers (1)

Andrei Gătej
Andrei Gătej

Reputation: 11934

I think you'll have to change from redirectTo: '/auth' to redirectTo: 'auth'. That is because when you're using absolute redirects(e.g /auth), only one redirect operation will be allowed, in this case the one which goes to /auth, meaning that any other redirects(e.g redirectTo: 'login') will be ignored.

Here's where it checks if there were any absolute redirects:

if (allowRedirects && this.allowRedirects) {
    return this.expandSegmentAgainstRouteUsingRedirect(
      ngModule, segmentGroup, routes, route, paths, outlet);
}

And here is where it states that after an absolute redirect, there can't be any other redirects:

if (e instanceof AbsoluteRedirect) {
  // after an absolute redirect we do not apply any more redirects!
  this.allowRedirects = false;
  // we need to run matching, so we can fetch all lazy-loaded modules
  return this.match(e.urlTree);
}

Absolute vs Relative Redirects

Excerpt from my GH repo.

The difference between redirectTo: 'foo/bar' and redirectTo: '/foo/bar' is that:

  • / - will start again from the root(the first outermost array of routes)
  • `` - will start the search from the first route from the array this current route resides in

Upvotes: 2

Related Questions