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

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

问题描述

假设我已经获得了此路由器配置

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

current route: /department/7/employees/45/sales

the old version will do: /department/7/employees/45/sales/contacts

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

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 });
    }

the update will do: /department/7/employees/45/contacts

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

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