我们假设我有这个路由器配置
export const EmployeeRoutes = [
{ path: 'sales', component: SalesComponent },
{ path: 'contacts', component: ContactsComponent }
];
已通过此网址导航至SalesComponent
/department/7/employees/45/sales
现在我想转到contacts
,但因为我没有绝对路线的所有参数(例如上面例子中的部门ID,7
)我会我喜欢使用相对链接到达那里,例如
[routerLink]="['../contacts']"
或
this.router.navigate('../contacts')
遗憾的是不起作用。可能有一个明显的解决方案,但我没有看到它。有人可以帮忙吗?
答案 0 :(得分:80)
如果您使用新路由器(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 });
}
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)
goToContact() {
this.router.navigate(["../contacts"], { relativeTo: this.r.parent });
}
the update will do: /department/7/employees/45/contacts
答案 1 :(得分:45)
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});