且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Angular-使用子路由延迟在模块内部加载模块

更新时间:2021-12-29 10:01:35

由于您希望在子路由更改的情况下加载新组件并将其作为延迟加载模块的一部分进行加载,因此可以添加一个<router-outlet></router-outlet>user-detail.component.html的模板.

Since you want a new component to be loaded in case of a child route change and load it as a part of a lazy-loaded module, you can add a <router-outlet></router-outlet> to the template of the user-detail.component.html.

类似这样的东西:

<h1>User Detail</h1>
<ul class="nav">
  <li class="nav-item">
    <a [routerLink]="['/users', user_id, 'user-albums']">User Albums</a>
  </li>
  <li class="nav-item">
    <a [routerLink]="['/users', user_id, 'user-favourites']">User Favourites</a>
  </li>
  <li class="nav-item">
    <a [routerLink]="['/users', user_id, 'user-stats']">User Stats</a>
  </li>
</ul>
<router-outlet></router-outlet>

现在,在此文件的模块中,定义一个路由配置以延迟加载各个模块:

Now, in the module of this file, define a route configuration to load the respective modules lazily:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Routes, RouterModule } from '@angular/router';

import { UserDetailComponent } from './user-detail.component';

const routes: Routes = [
  { 
    path: '', 
    component: UserDetailComponent,
    children: [
      {
        path: 'user-albums',
        loadChildren: './user-albums/user-albums.module#UserAlbumsModule'
      },
      {
        path: 'user-favourites',
        loadChildren: './user-favourites/user-favourites.module#UserFavouritesModule'
      },
      {
        path: 'user-stats',
        loadChildren: './user-stats/user-stats.module#UserStatsModule'
      },
    ]
  }
];

@NgModule({
  imports: [
    CommonModule,
    RouterModule.forChild(routes)
  ],
  declarations: [UserDetailComponent]
})
export class UserDetailModule { }

然后使用以下配置定义惰性模块:

And then define the lazy modules with their configuration like this:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Routes, RouterModule } from '@angular/router';

import { UserAlbumsComponent } from './user-albums.component';

const routes: Routes = [
  { path: '**', component: UserAlbumsComponent }
];

@NgModule({
  imports: [
    CommonModule,
    RouterModule.forChild(routes)
  ],
  declarations: [UserAlbumsComponent]
})
export class UserAlbumsModule { }

PS:由于有很多组件,建议您仔细看一下解决方案堆叠闪电战,以了解路由的接线方式.

PS: Since there are a lot of components, I'd suggest that you have a look at the solution stackblitz carefully in order to understand how the routing is wired in.

这是 工作示例StackBlitz 供您参考.

Here's a Working Sample StackBlitz for your ref.