【问题标题】:Lazy loading in Angular 6 resulting in Cannot match any routesAngular 6中的延迟加载导致无法匹配任何路由
【发布时间】:2019-04-10 05:46:11
【问题描述】:

我正在尝试在我的 Angular 应用程序中实现延迟加载。 这是我的路线:

app-routing.module.ts

const routes: Routes = [
  {
    path: '',
    loadChildren: './customer/customer.module#CustomerModule',
    pathMatch: 'full'
  }
];

在模块中:

  imports: [RouterModule.forRoot(routes)],

customer-routing.module.ts

export const routes: Routes = [
  { path: '', component: ComparePageComponent },
  { path: 'funds', component: FundSelectionComponent },
  { path: ':service', component: ComparePageComponent },
  { path: '**', component: PageNotFoundComponent },
];

在模块中:

imports: [
    RouterModule.forChild(routes)
  ],

现在,我有一个逻辑,可以在没有路径参数时加载 /profile 页面,即当 url 为 '' (this._router.navigate(['', 'profile'])) 时,我已经在我的客户模块 { path: ':service', component: ComparePageComponent } 中定义了路径

但是,当应用程序运行时,它会导致以下错误:

ERROR 错误:未捕获(在承诺中):错误:无法匹配任何路由。网址 段:'profile' 错误:无法匹配任何路由。网址段: '轮廓' 在 ApplyRedirects.push../node_modules/@angular/router/fesm5/router.js.ApplyRedirect

不确定我哪里出错了。

【问题讨论】:

  • 个人资料和服务是如何关联的?
  • @Sajeetharan profile 是 url 中的路径参数。 service 是我指定为 :service 的路径参数的占位符
  • @SiddAjmera,这也发生在 /funds 路径上。它没有采用客户模块中提到的任何路径
  • @SiddAjmera,你的意思是说我必须在 app-routing.module.ts 中有一个空路由的组件?
  • @SiddAjmera 是的,我是

标签: angular angular-routing


【解决方案1】:

您的AppRoutingModule 只有一条路由可以为用户加载CustomerModule。但这也是在一条空旷的路线上('')。

但是当您将用户导航到 /profile 路由时,Angular 会在您的 AppRoutingModule 中寻找与 'profile' 路径相对应的配置。

但是由于它无法在那里找到它,所以它抛出了这个错误。

为了让Angular超越空路径(''),它需要使用prefixpathMatch策略,除非你将其指定为full,否则默认使用该策略。

您可能想尝试从 AppRoutingModule 中的路由配置中删除 pathMatch: 'full' 以修复它。

【讨论】:

  • 从 AppRoutingModule 中删除 pathMatch: 'full' 并将其添加到 CustomerRoutingModule 解决了问题
  • 在提供空路径时,最佳实践是什么?我们应该在 AppRoutingModule 中使用 pathMatch 还是在 FeatureRoutingModule 中使用?我只是想确保我遵循最佳做法。
  • 这取决于要求。对于使用pathMatch,没有任何固定或固定的最佳实践。在这种情况下,我们希望 Angular 检查 prefixes 而不是完整的 path。因此我们不应该指定path,因为它的默认值是prefix,除非指定为full
【解决方案2】:

您有问题的导航路径。您应该使用/root 开始导航

this._router.navigate(['/', 'profile']))

【讨论】:

  • 这没有帮助
  • 客户模块路径'./customer/customer.module#CustomerModule'对吗?
  • 是的,这就是路径
  • 你能检查this._router.navigate(['/funds']))是否工作吗?
  • 从@SiddAjmera 的帖子中得到了答案。谢谢
猜你喜欢
  • 2021-08-25
  • 2019-01-13
  • 2018-12-11
  • 2018-05-09
  • 2018-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多