Tho*_*der 30 angular2-routing angular
在我的应用程序中,一些URL采用该表单
/department/:dep/employee/:emp/contacts
Run Code Online (Sandbox Code Playgroud)
在我的侧边栏中,我显示了所有员工的列表,每个员工都有一个[routerLink]链接到该员工联系人的员工
<ul>
<li>
<a [routerLink]="['/department', 1, 'employee', 1, 'contacts']"></a>
<li>
<li>
<a [routerLink]="['/department', 1, 'employee', 2, 'contacts']"></a>
<li>
...
</ul>
Run Code Online (Sandbox Code Playgroud)
然而,通过这种方法,我总是需要提供完整的路径,包括所有的参数(dep如上例所示),这非常麻烦.有没有办法提供路线的一部分,例如
<a [routerLink]="['employee', 2, 'contacts']"></a>
Run Code Online (Sandbox Code Playgroud)
(没有那个department部分,因为我并不真正关心department那个观点,而我的感觉是,这反对分离了关注点)?
Gün*_*uer 37
这应该有效.领先/使它成为绝对路线,没有它(或与./),它成为相对于当前路线的相对路线.您还可以使用../(或../../更多)相对于父级或父级父级路由.
如果您app-routing.module.ts看起来与此类似:
{
path: '/department/:dep', component: DepartmentComponent, children: [
{ path: 'employee/:emp/contacts', component: EmployeeComponent },
// ... Other child routes
]
}
Run Code Online (Sandbox Code Playgroud)
假设您在父路线上http://localhost:4200/department/1,现在下面routerLinks将按上述方式工作:
./代表当前路由的相对路径/表示从根路由开始的绝对路径../表示从当前路线向上移动一级的相对路径<ul>
<!-- will generate URL: http://localhost:4200/department/1/employee/1/contacts-->
<li class="nav-item">
<a class="nav-link" routerLink="recipes" routerLink="./employee/1/contacts">Relative Link that Works!:)</a>
</li>
<!-- is same as above and generated URL: http://localhost:4200/department/1/employee/1/contacts-->
<li class="nav-item">
<a class="nav-link" routerLink="recipes" routerLink="employee/1/contacts">Relative Link that Works!:)</a>
</li>
<!-- is same as above and generated URL: http://localhost:4200/department/1/employee/1/contacts-->
<li class="nav-item">
<a class="nav-link" routerLink="recipes" [routerLink]="['employee', '1', 'contacts']">Relative Link that Works! :)</a>
</li>
<!-- is NOT THE SAME as above and generated URL: http://localhost:4200/department/employee/1/contacts-->
<li class="nav-item">
<a class="nav-link" routerLink="recipes" routerLink="../employee/1/contacts">Relative Link that does NOT work! :( </a>
</li>
<!-- is NOT THE SAME as above and generated URL: http://localhost:4200/employee/1/contacts-->
<li class="nav-item">
<a class="nav-link" routerLink="recipes" routerLink="/employee/1/contacts">Absolute Link that does NOT work! :( </a>
</li>
</ul>
Run Code Online (Sandbox Code Playgroud)
我不知道你是否能与[routerLink]做到这一点,但你可以做到这一点像现在这样..
查看
<ul>
<li>
<a (click)="onViewDetails(id)">Details</a>
<li>
...
Run Code Online (Sandbox Code Playgroud)
零件
construct( private router: Router, private route: ActivatedRoute ){
}
onViewDetails(id){
this.router.navigate([id], {relativeTo: this.route});
}
Run Code Online (Sandbox Code Playgroud)
/员工
/员工/:id
建议不要在router.navigate函数中使用relativeTo参数,而不要使用“ ./”或“ ../” 。例如:
this.router.navigate(['child'], {relativeTo: this.route});
Run Code Online (Sandbox Code Playgroud)
要么
this.router.navigate(['sibling'], {relativeTo: this.route.parent});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
36408 次 |
| 最近记录: |