我如何导航到兄弟路线?

How do I navigate to a sibling route?

假设我得到了这个路由器配置

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

并已通过 URL

导航至 SalesComponent
/department/7/employees/45/sales

现在我想去 contacts,但是因为我没有绝对路径的所有参数(例如部门 ID,上例中的 7)我宁愿通过亲戚 link 到达那里,例如

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

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

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

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

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 所以

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

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

2021 年 12 月 12 日更新 Angular > 10

正如@ziz194 所提到的,这就是它现在的工作方式。

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

goToContact() {
  this.router.navigate(["contacts"], { relativeTo: this.r });
}

RouterLink 指令始终将提供的 link 视为当前 URL 的增量:

[routerLink]="['/absolute']"
[routerLink]="['../../parent']"
[routerLink]="['../sibling']"
[routerLink]="['./child']"     // or
[routerLink]="['child']" 

// with route param     ../sibling;abc=xyz
[routerLink]="['../sibling', {abc: 'xyz'}]"
// with query param and fragment   ../sibling?p1=value1&p2=v2#frag
[routerLink]="['../sibling']" [queryParams]="{p1: 'value', p2: 'v2'}" fragment="frag"

navigate() 方法需要一个起点(即 relativeTo 参数)。如果提供none,则导航是绝对的:

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

this.router.navigate(["/absolute/path"]);
this.router.navigate(["../../parent"], {relativeTo: this.route});
this.router.navigate(["../sibling"],   {relativeTo: this.route});
this.router.navigate(["./child"],      {relativeTo: this.route}); // or
this.router.navigate(["child"],        {relativeTo: this.route});

// with route param     ../sibling;abc=xyz
this.router.navigate(["../sibling", {abc: 'xyz'}], {relativeTo: this.route});
// with query param and fragment   ../sibling?p1=value1&p2=v2#frag
this.router.navigate(["../sibling"], {relativeTo: this.route, 
    queryParams: {p1: 'value', p2: 'v2'}, fragment: 'frag'});

// RC.5+: navigate without updating the URL 
this.router.navigate(["../sibling"], {relativeTo: this.route, skipLocationChange: true});