延迟加载模块路由的子级不起作用

时间:2021-05-03 10:19:07

标签: angular url-routing angular-router

我无法使延迟加载模块的路由正常工作。请查看此 stackblitz,它是 Angular lazy loading example 的副本,但有一些更改。

  • 首先,延迟加载本身似乎工作正常
  • 如果我点击“订单”按钮,模块就会(延迟)加载并显示正确的组件(OrdersComponent
  • 但是,点击“Orders Child”也会显示订单组件(而不是 OrdersComponent2
  • 当我取消注释子路由配置中的 pathMatch: 'full' 时,我会收到子路由的错误 Error: Cannot match any routes. URL Segment: 'orders/child'

我在这里做错了什么?

3 个答案:

答案 0 :(得分:2)

当你有 child-cmps 时,你不应该使用 pathMath: full

有两种可能

  1. 如果您的 orders2 应该嵌套在 orders 组件中,请向您的 orders 组件添加一个路由器出口。
<p>
  orders works!
</p>

<router-outlet></router-outlet>
  1. 将订单组件移至子组件:
const routes: Routes = [
  {
    path: "",
    children: [
      {
        path: "",
        component: OrdersComponent
      },
      {
        path: "child",
        component: OrdersComponent2
      }
    ]
  }
];

编辑:

或删除子项并像这样设置:

const routes: Routes = [
  {
    path: "",
    component: OrdersComponent
  },
  {
    path: "child",
    component: OrdersComponent2
  }
];

让我知道这是否有帮助

答案 1 :(得分:1)

您将 OrdersComponent2 定义为 OrdersComponent 的子路由:这与延迟加载模块无关。它们属于同一个模块,一旦导航到 /orders 就会延迟加载。

您通过点击“Order Child”按钮正在导航到子路径 /orders/child:要使其工作,您需要在 <router-outlet> 中使用 orders.component.html template。 Angular 将使用该出口来显示子视图。

Updated Stackblitz

答案 2 :(得分:0)

在您的 orders-routing-module.ts 中,问题在于您指定路径的位置:

path: "child",

没有带有选择器“app-child”的组件,所以它会给你“无法匹配任何路由”错误。您的 orders.component.ts 具有带有选择器的子组件 “app-orders-2”,所以试试这个路径,错误应该消失,内容显示:

path: "orders-2",