导航回到父URL

时间:2019-10-10 10:36:54

标签: angular typescript angular-routing

当选项更改且路由参数更多时,我尝试导航回父URL,如果没有路由参数,则保留当前URL。

我会给你一个例子,使一切更加清楚。

因此,我有3个组件: CompA CompB CompC ,其中包含项目列表,当我导航到其中一个项目时我保留网址:

/ compA / compB / compC

可以在每个组件内部导航到一个项目,并且也可以将URL保留为 / compA / item1

我有一个下拉列表来选择特定的客户端,我想要的是在更改客户端并且具有路由参数时导航回父级,如果没有,则保留特定的路由。 t。

例如,我在 / compA / item2 上,我更改了客户端。预期的行为是导航到 / compA 。或者,如果我在 / compB 上并且更改了客户端,则应该保留在 / compB

我找到了使用这个的解决方案

this.router.navigate(['.'], { relativeTo: this.activeRoute.parent });

但不适用于我。

2 个答案:

答案 0 :(得分:0)

由于.是“当前目录”,所以../是“上一级”

this.router.navigate(['../'], { relativeTo: this.activeRoute.parent });

答案 1 :(得分:0)

我使用以下方法找到了解决方案:

const parentURL = this.router.url.split('/')[1];
this.router.navigate([parentURL]);