【问题标题】:Lazy Loading results in ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment:延迟加载导致 ERROR 错误:未捕获(在承诺中):错误:无法匹配任何路由。网址段:
【发布时间】:2020-02-19 14:53:41
【问题描述】:

我实现了延迟加载并导致此错误。我看过很多帖子,但没有一个给出解决方案。

如何重现:

  1. 转到https://stackblitz.com/edit/angular-sxmpj8
  2. 点击订单标签
  3. 点击测试

预期:它会打开测试组件 实际:导致“未捕获(承诺中):错误:无法匹配任何路由。URL段:”错误

我正在尝试延迟加载具有两个组件订单和测试的订单模块。订单路线工作正常,但测试组件路线抛出错误。

申请地址为https://stackblitz.com/edit/angular-sxmpj8

在 orders-routing.module.ts 中路由定义如下:

    const routes: Routes = [
  {
    path: '',
    component: OrdersComponent,

    children: [
      { path: 'test', component: TestComponent
  }]
  }
];

app-routing.module.ts 中的路由定义如下。

const routes: Routes = [
  {
    path: 'customers',
    loadChildren: () => import('./customers/customers.module').then(m => m.CustomersModule)
  },
  {
   path: 'orders',

   // Tried this also
   // loadChildren:  './orders/orders.module#OrdersModule'
    loadChildren: () => import('./orders/orders.module').then(m => m.OrdersModule)
  },
  {
    path: '',
    redirectTo: '',
    pathMatch: 'full'
  }
];

在 orders.component.ts 文件中我有一个条目

<button routerLink="/test">Test</button>

点击这个结果报错

错误 错误:未捕获(承诺):错误:无法匹配任何路由。 URL 段:“测试” 错误:无法匹配任何路由。 URL 段:“测试”

【问题讨论】:

  • 您是否尝试重新启动服务器(运行ng serve)?
  • 是的,没有运气。刷新 npm 缓存,运行 npm install
  • @Ningomba 我知道你在烦恼什么,但我不明白你想要什么?如果点击测试用户要去哪里?

标签: angular angular2-routing


【解决方案1】:

有两个问题:

  1. 由于您的测试组件设置为子路由,因此您需要一个模块级别的 &lt;router-outlet&gt; 以便 Angular 路由器知道在哪里呈现您的测试组件。
  2. 在“测试”按钮上,您需要指定整个路由(包括/orders)。

我分叉了你的 stackblitz,所以你可以在这里看到它的工作 => https://stackblitz.com/edit/angular-sxmpj8-q9xzzv

【讨论】:

  • 太棒了!很高兴为您提供帮助!
【解决方案2】:

首先routerLink应该是一个相对路径,否则会到app的根目录,并且app路由上没有定义/test路径。 routerLink 中的相对路径是相对于当前 router-outlet 的相对路径,routerLink 是在其中定义的。

其次,orders.component.html 也需要&lt;router-outlet&gt;&lt;/router-outlet&gt;,否则测试组件不会放在任何地方。

类似这样的:

<button routerLink="test">Test</button>
<router-outlet></router-outlet>

working example

【讨论】:

    【解决方案3】:

    您需要添加routerLink="/orders/test" 而不仅仅是routerLink="/test"。 您还需要在 orders.component.html 中添加 &lt;router-outlet&gt;&lt;/router-outlet&gt; 以显示 testComponent 的视图。

    更改orders.component.html

         <p>
          orders works!
        </p>
    
        <button routerLink="/orders/test">Test</button>
        <router-outlet></router-outlet>
    

    希望对你有帮助!!

    【讨论】:

    • @Ningomba 查看解决方案。
    • @Ningomba 很高兴能为您提供帮助 :)
    【解决方案4】:

    试试这个:

    <button routerLink="/orders">Test</button>
    

    在订单路由模块中修改后:

    const routes: Routes = [
      {
        path: '',
        component: OrdersComponent
      }
    ]
      }
    ];
    

    【讨论】:

      猜你喜欢
      • 2019-02-01
      • 2020-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-18
      • 2019-10-14
      • 2022-06-14
      • 2023-02-11
      相关资源
      最近更新 更多