Search code examples
angularlazy-loadingangular-routing

Angular Lazy Loading loading same route again


https://stackblitz.com/github/sandypm2020/BookStore

<ul class="leftNav">
  <li>
    <a routerLink="/books">Books</a>
  </li>
  <li>
    <a routerLink="/users">Users</a>
  </li>
</ul>
const routes: Routes = [
  {
    path: 'books',
    loadChildren: () => import('./book/book.module').then((m) => m.BookModule),
  },
  {
    path: 'users',
    loadChildren: () => import('./user/user.module').then((m) => m.UserModule),
  },
  { path: '', pathMatch: 'full', redirectTo: 'books' },
];

Guys I want to use lazy loading I have following routes and URLs. But for some reason when I go to user it loads books route again can someone help why that is happening?


Solution

  • First: change href to routerLink like the following :

    <ul class="leftNav">
            <li>
              <a routerLink="/books">Books</a>
            </li>
            <li>
              <a routerLink="/users">Users</a>
            </li>
      </ul>
    

    Then go to UserModule and add the routes to import section like the following :

    @NgModule({
      declarations: [UserListComponent, AddUserComponent, UserEditComponent],
      imports: [CommonModule, RouterModule.forChild(routes)],
    })
    export class UserModule {}