Tho*_*der 51 angular2-routing angular2-router angular
我们假设我得到了这个路由器配置
export const EmployeeRoutes = [
{ path: 'sales', component: SalesComponent },
{ path: 'contacts', component: ContactsComponent }
];
Run Code Online (Sandbox Code Playgroud)
并已导航SalesComponent到此URL
/department/7/employees/45/sales
Run Code Online (Sandbox Code Playgroud)
现在我想去contacts,但因为我没有绝对路线的所有参数(例如7上面例子中的部门ID ),我宁愿使用相对链接到达那里,例如
[routerLink]="['../contacts']"
Run Code Online (Sandbox Code Playgroud)
要么
this.router.navigate('../contacts')
Run Code Online (Sandbox Code Playgroud)
不幸的是,这不起作用.可能有一个明显的解决方案,但我没有看到它.有人可以帮帮忙吗?
Har*_*inh 89
如果您使用的是新路由器(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 });
}
Run Code Online (Sandbox Code Playgroud)
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 });
}
Run Code Online (Sandbox Code Playgroud)
the update will do: /department/7/employees/45/contacts
Mar*_*cok 49
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"
Run Code Online (Sandbox Code Playgroud)
该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});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
32682 次 |
| 最近记录: |