67

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

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

SalesComponent并已通过此 URL导航到

/department/7/employees/45/sales

现在我想去contacts,但由于我没有绝对路线的所有参数(例如,7在上面的示例中,部门 ID)我更喜欢使用相对链接到达那里,例如

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

或者

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

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

4

2 回答 2

118

如果您使用的是新路由器(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 });
}

更新 2019 年 8 月 2 日 Angular 7.1.0

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

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

根据@KCarnaille 的评论,以上不适用于最新的路由器。新的方法是添加.parentthis.rso

    // 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

更新 12/12/2021 角度 > 10

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

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

goToContact() {
  this.router.navigate(["contacts"], { relativeTo: this.r });
}
于 2016-07-28T11:00:55.423 回答
83

RouterLink 指令始终将提供的链接视为当前 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参数)。如果没有提供,导航是绝对的:

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});
于 2016-08-06T19:41:59.967 回答