Relative links/partial routes with routerLink

与世无争的帅哥 提交于 2019-12-20 10:22:19

问题


In my app some URLs take the form

/department/:dep/employee/:emp/contacts

In my sidebar I show a list of all employees, each of which has a [routerLink] which links to that employee's contacts

<ul>
    <li>
        <a [routerLink]="['/department', 1, 'employee', 1, 'contacts']"></a>
    <li>
    <li>
        <a [routerLink]="['/department', 1, 'employee', 2, 'contacts']"></a>
    <li>
    ...
</ul>

However, with this approach I always need to provide the full path, including all the params (like dep in the above example) which is quite cumbersome. Is there a way to provide just part of the route, such as

<a [routerLink]="['employee', 2, 'contacts']"></a>

(without the department part, because I don't really care about department in that view and my feeling is that this goes against separation of concerns anyway)?


回答1:


That's supposed to work. The leading / makes it an absolute route, without it (or with ./), it becomes a relative route relative to the current route. You can also use ../ (or ../../ or more) to route relative to the parent or parents parent.




回答2:


I don't know if you can do it with [routerLink] but you can do it like so..
View

<ul>
    <li>
        <a (click)="onViewDetails(id)">Details</a>
    <li>
    ...

Component

construct( private router: Router, private route: ActivatedRoute ){
}
onViewDetails(id){
 this.router.navigate([id], {relativeTo: this.route});
}

/employee
/employee/:id




回答3:


Instead of using './' or '../', I would suggest using relativeTo param in router.navigate function. E.g.:

this.router.navigate(['child'], {relativeTo: this.route});

or

this.router.navigate(['sibling'], {relativeTo: this.route.parent});


来源:https://stackoverflow.com/questions/38212529/relative-links-partial-routes-with-routerlink

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!