首页 > 解决方案 > 延迟加载另一个模块时路由中断

问题描述

我有一个延迟加载的模块AccountModule,它在访问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有两条子路线。其中一个被急切加载(/overview),而另一个被延迟加载(/albums)。

因此,acount.routing.ts看起来像这样:

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);

现在,如果我使用“eager”加载(component:AlbumsComponent)一切正常。但是,如果我切换到loadChildren: () => ...路由不再起作用。这routerLink

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

结果https://localhost:4201/account/albums(工作)或https://localhost:4201/account/albums/overview(不工作)。但为什么?我该如何解决这个问题?

为什么仅仅因为模块/组件的加载方式而表现不同?


如果我将路径设置为./albums

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

我只是得到

错误:无法匹配任何路由。网址段:'account/albums'

标签: angular

解决方案


我猜你还没有为 albums.routing.module 提供路线?

由于您已经指导了 albums.module,但您可能没有从那里提供您所展示的组件。

如果您尚未创建到 albums.routing.module,请创建一个并在同一模块中提供默认路由。

const routes: Routes = [

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

推荐阅读