【问题标题】:Angular 9 Universal and lazy loaded routesAngular 9 通用和延迟加载的路由
【发布时间】:2020-07-31 17:37:25
【问题描述】:

快速提问;我找不到有关此问题的任何文档。 在以前的 Angular Universal 版本中,要在 查看源代码 中呈现延迟加载的路由,您必须在 app.server.module.ts 中包含 ModuleMapLoaderModule

在 Angular 9 中,如果您没有为 loadChildren 使用字符串,您似乎不必这样做。 我有一个新项目,我设置了这样的延迟加载:

const routes: Routes = [
  {
    path: '',
    loadChildren: () =>
      import('./brands/brands.module').then((m) => m.BrandsModule),
  },
  { path: '**', redirectTo: '' },
];

如果我查看页面源,我看不到我的 BrandsComponent 但如果我将路由更改为:

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

查看页面源代码会显示 BrandsComponent,它告诉我延迟加载不起作用。 有谁知道如何解决这个问题?

【问题讨论】:

    标签: angular angular-universal


    【解决方案1】:

    文档中的Lazy loading basics 有点误导。

    你应该仔细阅读Step-by-step setup

    我认为结构应该是这样的:

    app-routing.module.ts

    const routes: Routes = [
      {
        path: '',
        loadChildren: () =>
          import('./brands/brands.module').then((m) => m.BrandsModule),
      },
      { path: '**', redirectTo: '' },
    ];
    

    brands-routing.module.ts

    import { NgModule } from '@angular/core';
    import { Routes, RouterModule } from '@angular/router';
    import { BrandsComponent } from './brands.component';
    
    const routes: Routes = [
      {
        path: '',
        component: BrandsComponent
      }
    ];
    
    @NgModule({
      imports: [RouterModule.forChild(routes)],
      exports: [RouterModule]
    })
    export class BrandsRoutingModule { }
    

    brands.module.ts

    import { NgModule } from '@angular/core';
    import { CommonModule } from '@angular/common';
    import { BrandsRoutingModule } from './brands-routing.module';
    import { BrandsComponent } from './brands.component';
    
    @NgModule({
      imports: [
        CommonModule,
        BrandsRoutingModule
      ],
      declarations: [BrandsComponent]
    })
    export class BrandsModule { }
    

    【讨论】:

    • 不是这个,实际上我在品牌路线上有一个导致问题的解析器,但这是一个很好的明确答案,可以帮助大多数人,所以我接受了它
    • @r3plica 您最好发布另一个解决您问题的答案。
    • 对不起,我没明白你在原始代码 sn-p 中究竟做了什么改动?
    猜你喜欢
    • 2020-10-30
    • 2017-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多