【问题标题】:Lazy load same module from different paths从不同的路径延迟加载相同的模块
【发布时间】:2020-04-27 13:50:18
【问题描述】:

我有关注app-routing.module.ts

  {
    path: 'discover',
    loadChildren: () => import('./components/platform/user-profile/platform.module').then(m => m.PlatformModule)
  },
  {
    path: ':userRoute',
    loadChildren: () => import('./components/platform/user-profile/platform.module').then(m => m.PlatformModule)
  },

我的目标是 /discover 应该从 PlatformModule 打开 DiscoverPageComponent

/userName1 应该从 PlatformModule 打开 UserPageComponent

我的platform-routing.module.ts 包含以下内容:

  {
    path: '',
    component: UserProfileComponent,
  },
  {
    path: 'discover',
    component: DiscoverPageComponent,
  },

这不起作用,因为 /discover 将始终打开 UserProfileComponent 而不是 DiscoverPageComponent。我只能从 /userName1/discover 中打开 DiscoverPageComponent

如何让这两个不同的路由从同一个延迟加载模块打开它们的特定组件?

Stackblitz: https://stackblitz.com/edit/angular-w3rc5g 请参阅 /discover 和 /anyUserName1

【问题讨论】:

  • 你能在 stackblitz 上重现它吗?
  • 部分修复 - 在 platform-routing.module.ts 中将 UserProfileComponent 替换为 DiscoverPageComponent 并将 DiscoverPageComponent 替换为 UserProfileComponent 。现在/discover 打开DiscoverPageComponent
  • 我建议您使用带有路由器插座的平台容器.component.ts 之类的东西。然后你在''路径定义你的容器并定义children: [ { path: ' ', component: UserProfileComponent }, { path: 'DiscoverPageComponent ', component: DiscoverPageComponent }, ] 这个设置将起作用。
  • @piyushjain 现在任何东西都会打开 DiscoverPageComponent 但没有任何东西会打开 UserPageComponent :)
  • @MikeS。我添加了一个堆栈闪电战

标签: angular angular-router


【解决方案1】:

试试下面的示例代码,更改你的路由模块

在 app-routing.moudle.ts 中:

const routes: Routes = [
  {
    path: '',
    loadChildren: () => import('./platform/platform.module').then(m => m.PlatformModule)
  },
];

在platform-routing.module.ts中:

const routes: Routes = [
  {
    path: "user",
    children: [
      {
        path: ":user",
        component: UserProfileComponent
      }
    ]
  },
  {
    path: "discover",
    component: DiscoverComponent
  },
  {
    path: "",
    redirectTo: "discover",
    pathMatch: "full"
  }
];
  1. http://localhost:4200/discover
  2. http://localhost:4200/user/1

【讨论】:

  • 我还建议将用户路由命名为 user/:user 而不仅仅是 :user
  • 我无法更改用户路线。 instagram.com/example 看起来比 instagram.com/user/example 更好
猜你喜欢
  • 2019-11-27
  • 2018-09-01
  • 2018-06-11
  • 1970-01-01
  • 2019-09-03
  • 2019-04-22
  • 2020-01-12
  • 2019-01-05
  • 1970-01-01
相关资源
最近更新 更多