【问题标题】:How to set up routing properly in a dynamically loaded Angular module?如何在动态加载的 Angular 模块中正确设置路由?
【发布时间】:2020-01-22 13:49:34
【问题描述】:

我有一个带有路由器插座的应用程序,我想在其中延迟加载带有自己子路由的模块。

这应该给出路线:

/
/lazy1/child1
/lazy1/child2

在根应用模块中,我定义了一些将延迟加载子模块的路由

export const routes: Routes = [
  {path:'', component: HelloComponent},
  {path: 'lazy1', loadChildren: () => import('./lazy1-module/index').then(mod => mod.Lazy1Module)}
];

在 Lazy1Module 中,以下路线

const routes: Routes = [
 {path: 'child1', component: Child1Component},
 {path: 'child2', component: Child2Component},
 {path: '**', redirectTo: 'child1'}
];

我像往常一样使用 RouterModule.forChild(routes) 添加。

这似乎工作正常,当我转到 /lazy1/child1 时,这解决得很好。

但是,当我尝试在孩子之间导航时,我遇到了麻烦。 由于其自身的延迟加载模块不应该知道或关心自身外部的路由,我假设我可以使用

从 child1 导航到 child2
this.router.navigate(["child2"]);

这会导致“找不到路由”错误。

我可以通过添加使其工作

this.router.navigate(["child2"], { relativeTo: this.route.parent });

但这似乎是错误的。 “../child2”也不起作用。

向路由器添加日志记录,似乎它在路由前面添加了一个“/”并开始从根目录解析它,也忽略任何点。

我正在使用 Angular 8.2.14

此处为 Stackblitz 示例:https://stackblitz.com/edit/angular-bqdchr

【问题讨论】:

  • this.router.navigate(['/lazy/child2']);
  • 感谢您的评论,但是我尽量不使用绝对路径,因为延迟加载的模块可能会在不同的上下文中加载,并且不一定将“延迟”作为父级。

标签: angular routing


【解决方案1】:

看看这个stackblitz:

我认为这是因为你的惰性路由不知道它自己的根所以你需要添加:

path:'', component: LazyComponent, children: [
  { path: 'child1', component: Child1Component },
  { path: 'child2', component: Child2Component }
]

【讨论】:

  • 我查看了 stackblitz,它在 LazyComponent 中有第二个路由器插座,而我没有。我知道这可以如何解决我的问题,但我希望不要仅仅因为另一个层。
  • 啊我明白你的意思了。
【解决方案2】:

您可以通过绝对或相对路径导航。

this.router.navigate(['child2']);

正在使用绝对路径(因为没有relativeTo 标志)并导航到/child2。 您没有为 /child2 但为 /lazy1/child2 定义路由。

控制台错误告诉你:

错误:无法匹配任何路由。网址段:'child2'

如果你将它重写为:

this.router.navigate(['lazy1', 'child2']);

您的工作示例使用的是相对路径:

this.router.navigate(["child2"], { relativeTo: this.route.parent });

您当前路由的父级是lazy。从那里您将导航到child2,这是一条有效路线 (/lazy/child2)。

请参阅https://angular.io/api/router/Router#navigate 了解更多信息。 以下内容也可能很有趣:https://angular.io/guide/router#router-links

【讨论】:

  • Thanx Steven,这也是我发现的一个很好的记录。那么你会同意还是不同意我的这种行为很奇怪?我假设导航到“child2”(不是“/child2”)将导航到同级或子路径,而不是根子路径。我的用例是尝试动态加载一个模块,该模块可以附加在根目录(在这种情况下它可以工作)或在示例中的上下文中。
【解决方案3】:

你的懒惰路线:

const routes: Routes = [
  {path:'',children:[
    {path: 'child1', component: Child1Component},
    {path: 'child2', component: Child2Component}
  ]},
 {path: '**', redirectTo: 'child1'}
];

那么,你就可以了

this.router.navigate(["child2"], { relativeTo: this.route.parent });
//or
this.router.navigate(["../child2"],{ relativeTo: this.route});

【讨论】:

  • 你试过了吗?在我看来这没有什么区别,我仍然必须添加 relativeTo 属性。不过,我真的很感谢你的努力:) 我真的很难理解预期的默认行为应该是什么。对我来说,不需要添加 relativeTo 属性,因为默认应该是活动路由父级。我应该向 Angular 团队提交错误,还是按某种方式真的有意义?
  • 你的分叉堆栈闪电战:stackblitz.com/edit/…
猜你喜欢
  • 1970-01-01
  • 2017-04-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-10
  • 2020-01-20
  • 1970-01-01
  • 2016-12-28
相关资源
最近更新 更多