【问题标题】:Children of Lazy Loaded Modules routes don't work延迟加载模块路由的子节点不起作用
【发布时间】:2021-05-03 10:19:07
【问题描述】:

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

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

我在这里做错了什么?

【问题讨论】:

    标签: angular url-routing angular-router


    【解决方案1】:

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

    有两种可能

    1. 如果您的订单 2 应该嵌套在订单组件中,请向订单组件添加路由器出口。
    <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
      }
    ];
    

    如果有帮助请告诉我

    【讨论】:

      【解决方案2】:

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

      您通过单击“订购子”按钮正在执行的操作是导航到子路由 /orders/child:为此,您需要在 orders.component.html template 中添加一个 &lt;router-outlet&gt;。 Angular 将使用该插座来显示子视图。

      Updated Stackblitz

      【讨论】:

        【解决方案3】:

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

        path: "child",
        

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

        path: "orders-2",
        

        【讨论】:

        • 只是给你一些反馈:路径与组件选择器无关。路径是浏览器中的 url,其中包含您定义调用哪个组件的属性组件。希望这对你有帮助:)
        • 这是有道理的,但是为了最佳实践,路径应尽可能与组件选择器相对应。我同意子“子”组件应该是 Order 子文件夹中的一个组件,它有自己的路由模块。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-21
        • 1970-01-01
        • 1970-01-01
        • 2018-10-04
        • 1970-01-01
        相关资源
        最近更新 更多