Stefan Falk
Stefan Falk

Reputation: 25447

Routing breaks when lazy loading another module

I have a lazy loaded module AccountModule which gets loaded after accessing https://localhost:4201/account.

app.routing.ts

const routes: Routes = [

  {
    path: '',
    loadChildren: () => import('./ui/pages/start/start.module')
      .then(m => m.StartModule)
  },


  {
    path: 'account',
    loadChildren: () => import('./ui/pages/account/account.module')
      .then(m => m.AccountModule)
  },

];

export const AppRouting = RouterModule.forRoot(routes, {
  useHash: false,
  enableTracing: false
});

AccountModule has two child routes. One of which gets loaded eagerly (/overview) whereas the other gets loaded lazily (/albums).

Hence, acount.routing.ts looks like this:

const routes: Routes = [

  {path: '', redirectTo: 'overview', pathMatch: 'full'},

  {
    path: 'overview',
    component: AccountComponent,
  },

  {
    path: 'albums',
    loadChildren: () => import('./albums/albums.module').then(m => m.AlbumsModule),
    // component: AlbumsComponent  // This works!
  },

];

export const AccountRouting = RouterModule.forChild(routes);

Now, if I use "eager" loading (component:AlbumsComponent) everything is working. But, if I switch to loadChildren: () => ... routing does not work anymore. This routerLink

<app-raised-button [routerLink]="['/account/albums']">
  My Albums
</app-raised-button>

Results in https://localhost:4201/account/albums (working) or https://localhost:4201/account/albums/overview (not working). But why? And how can I fix this issue?

Why does it behave differently just because of the way the module/component gets loaded?


If I am setting the path to ./albums:

{
  path: './albums',
  loadChildren: () => import('./albums/albums.module').then(m => m.AlbumsModule),
},

I am just getting

Error: Cannot match any routes. URL Segment: 'account/albums'

Upvotes: 0

Views: 926

Answers (2)

STEVE  K.
STEVE K.

Reputation: 919

Make sure in your albums module , you have your have imported your routes as shown : RouterModule.forChild(albumsRoutes)

Upvotes: 0

Sats
Sats

Reputation: 1973

I guess you have not provided a Routes for albums.routing.module ?

Since you have directed the albums.module, but you might have not provided from there what component you have been show.

If you have not created to albums.routing.module, create one and provide a default route in the same module.

const routes: Routes = [

  {path: '', component:AlbumsComponent } ];

Upvotes: 2

Related Questions