如何导航到兄弟路线? [英] How do I navigate to a sibling route?

查看:39
本文介绍了如何导航到兄弟路线?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这个路由器配置

Let's presume I got this router config

export const EmployeeRoutes = [
   { path: 'sales', component: SalesComponent },
   { path: 'contacts', component: ContactsComponent }
];

并已通过此 URL 导航到 SalesComponent

and have navigated to the SalesComponent via this URL

/department/7/employees/45/sales

现在我想转到 contacts,但是因为我没有绝对路径的所有参数(例如部门 ID,7 在上面的例子)我更喜欢使用相对链接到达那里,例如

Now I'd like to go to contacts, but as I don't have all the parameters for an absolute route (e.g. the department ID, 7 in the above example) I'd prefer to get there using a relative link, e.g.

[routerLink]="['../contacts']"

this.router.navigate('../contacts')

不幸的是它不起作用.可能有一个明显的解决方案,但我没有看到.有人可以帮忙吗?

which unfortunately doesn't work. There may be an obvious solution but I'm not seeing it. Can anyone help out here please?

推荐答案

如果您使用的是新路由器(3.0.0-beta2),您可以使用 ActivatedRoute 导航到相对路径,如下所示:

If you are using the new router (3.0.0-beta2), you can use the ActivatedRoute to navigate to relative path as follow:

constructor(private router: Router, private r:ActivatedRoute) {} 

///
// DOES NOT WORK SEE UPDATE
goToContact() {
  this.router.navigate(["../contacts"], { relativeTo: this.r });
}

更新 08/02/2019 Angular 7.1.0

当前路线:/department/7/employees/45/sales

旧版本:/department/7/employees/45/sales/contacts

根据@KCarnaille 的评论,上述内容不适用于最新的路由器.新的方式是将 .parent 添加到 this.r so

As per @KCarnaille's comment the above does not work with the latest Router. The new way is to add .parent to this.r so

    // Working(08/02/2019) 
    goToContact() {
       this.router.navigate(["../contacts"], { relativeTo: this.r.parent });
    }

更新将执行:/department/7/employees/45/contacts

这篇关于如何导航到兄弟路线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆