【问题标题】:Lazy load different layouts - angular 9延迟加载不同的布局 - 角度 9
【发布时间】:2020-04-12 12:14:51
【问题描述】:

我正在用 Angular 9 构建一个应用程序,但我对这一切还是很陌生。我想根据路线延迟加载不同的布局。我发现我应该这样做:

在我的 app.routes.ts

{
    path: 'home',
    component: MainLayoutComponent,
    loadChildren: () => import('./main/pages/home/home.module').then(m => m.HomeModule)
},
{
    path: 'settings',
    component: DifferentLayoutComponent,
    loadChildren: () => import('./main/pages/settings/settings.module').then(m => m.SettingsModule)
}

但是这样做我是否急切地加载所有布局组件?如果我有 10 种不同的布局,我会在导航到单个页面时加载所有这些布局吗?

【问题讨论】:

    标签: angular angular-routing


    【解决方案1】:

    根据您在问题中提到的路线。您有两个模块 HomeModuleDifferentLayoutComponent。当用户访问其对应路径时,将下载这两个模块块。一旦访问过该模块,如果再次访问该路径,将不会再次下载,因为我们已经下载了它。如果要在初始模块热加载后下载其他模块,可以使用预加载策略

    【讨论】:

    • 也许我没有很好地解释自己。你说的对settings.module和home.module有效。但是 MainLayoutComponent 和 DifferentLayoutComponent 呢?如果我访问 home 路由,DifferentLayoutComponent 会被急切加载吗?
    【解决方案2】:

    我所做的是将不同的布局作为一个模块加载到应用程序路由模块中,如下所示 (app-routing.module.ts):

    {
        path: '',
        loadChildren: () => import('../different-layout/different-layout.module').then(m => m.DifferentLayoutModule)
    }
    

    然后在 DifferentLayoutModule 中添加这样的路由:(different-layout-routing.module.ts)

    {
        path: '',
        component: DifferentLayoutComponent,
        children: [
            {
                path: 'foo',
                component: FooComponent
            }
        ]
    }
    

    当然,不同的布局组件应该看起来像这样 (different-layout.component.html):

    <app-header></app-header>
    <router-outlet>
       Here it will be injected your foo component
    </router-outlet>
    <app-footer></app-footer>
    

    【讨论】:

      猜你喜欢
      • 2020-12-03
      • 1970-01-01
      • 1970-01-01
      • 2018-05-22
      • 2013-08-06
      • 2018-02-27
      • 2017-12-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多