【问题标题】:Angular lazy loading module based on URL parameter基于 URL 参数的 Angular 延迟加载模块
【发布时间】:2019-03-30 06:44:55
【问题描述】:

我正在开发一个 Angular 7 应用程序,现在正在基于路由设置延迟加载模块。我想根据 URL 参数延迟加载不同的模块。我似乎无法弄清楚如何让它发挥作用。

这是 UI 的构造示意图:

我想要发生的是这样的路径:

/page/type-of-items/type-of-item 加载应用程序,然后延迟加载页面模块,然后根据@987654323 的值延迟加载正确的“项目类型”模块@ 在 URL 中,然后它将根据 URL 加载正确的 :item 组件。

问题在于,当访问此 URL:/page/foo/item-a 时,NotFoundPageComponent 会被渲染。我在这里做错了什么?

这是我目前的路由模块集:

app-routing.module:

const routes: Routes = [
  {
    path: 'page',
    loadChildren: './page.module#PageModule'
  },
  {
    path: '**',
    component: NotFoundPageComponent
  }
];

page.module:

const routes: Routes = [
  {
    path: ':type-of-items',
    component: PageComponent
  },
  {
    path: 'foo',
    loadChildren: '../foo.module#FooModule'
  }
];

注意PageComponent 需要知道:type-of-items 的值才能获取一些上下文数据,这就是它被参数化的原因。在这种情况下,它的值是“foo”。

foo.module:

const routes: Routes = [
  {
    path: '',
    component: FooComponent,
    children: [
      {
        path: 'item-a',
        component: ItemAComponent
      },
      {
        path: 'item-b',
        component: ItemBComponent
      }
    ]
  }
];

【问题讨论】:

  • 我的猜测是,在您的page.module 路由中,路径与':type-of-items' 路径匹配,并且没有机会到达'foo'。将page.module 中的路线顺序颠倒,最具体的在前。
  • 感谢@JasonWhite,但结果相同。
  • foo模块在page模块里面吗?还是它们在同一目录级别?我问的原因是 foo 模块的延迟加载路径是 ../ 而不是 ./
  • 我简化了模块的路径。我不担心路径是否正确,因为如果路径不正确会引发错误 - 我没有看到。

标签: angular


【解决方案1】:

试试这个

const routes: Routes = [
{ path: '', 
  component: SomeTopLevelComponent, // might not need
  children: [{
    path: 'page',
    loadChildren: './page.module#PageModule'
  }]},
  {
    path: '**',
    component: NotFoundPageComponent
  }
];

【讨论】:

  • 另外,当我给出模块的位置时,我必须从 'app/modules/moduleName.module#moduleNameModule' 开始
猜你喜欢
  • 2017-02-22
  • 2020-01-10
  • 1970-01-01
  • 1970-01-01
  • 2019-12-02
  • 1970-01-01
  • 1970-01-01
  • 2018-05-22
  • 2022-10-17
相关资源
最近更新 更多