在我的应用中,某些网址采用
形式/department/:dep/employee/:emp/contacts
在我的侧边栏中,我会显示所有员工的列表,每个员工都有一个[routerLink]
链接到该员工的联系人
<ul>
<li>
<a [routerLink]="['/department', 1, 'employee', 1, 'contacts']"></a>
<li>
<li>
<a [routerLink]="['/department', 1, 'employee', 2, 'contacts']"></a>
<li>
...
</ul>
然而,通过这种方法,我总是需要提供完整路径,包括所有参数(如上例中的dep
),这非常麻烦。有没有办法提供路线的一部分,例如
<a [routerLink]="['employee', 2, 'contacts']"></a>
(没有department
部分,因为在这种观点中我并不真正关心department
,而我的感觉是,这反过来又不利于关注点分离?)
答案 0 :(得分:32)
这应该有效。前导/
使其成为绝对路线,没有它(或使用./
),它将成为相对于当前路线的相对路线。您还可以使用../
(或../../
或更多)来相对父母或父母进行路由。
答案 1 :(得分:5)
我不知道你是否可以用[routerLink] 来做,但你可以这样做..
视图的
<ul>
<li>
<a (click)="onViewDetails(id)">Details</a>
<li>
...
组件
construct( private router: Router, private route: ActivatedRoute ){
}
onViewDetails(id){
this.router.navigate([id], {relativeTo: this.route});
}
/ employee
/ employee /:id
答案 2 :(得分:2)
如果您的app-routing.module.ts
看起来像这样:
{
path: '/department/:dep', component: DepartmentComponent, children: [
{ path: 'employee/:emp/contacts', component: EmployeeComponent },
// ... Other child routes
]
}
假设您在父路线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>
答案 3 :(得分:0)
建议不要在router.navigate函数中使用 relativeTo 参数,而不要使用“ ./”或“ ../”。例如:
this.router.navigate(['child'], {relativeTo: this.route});
或
this.router.navigate(['sibling'], {relativeTo: this.route.parent});