2016-07-28 54 views
29

咱們怙我得到這個路由器配置我如何導航到兄弟路線?

export const EmployeeRoutes = [ 
    { path: 'sales', component: SalesComponent }, 
    { path: 'contacts', component: ContactsComponent } 
]; 

,並通過這個網址

/department/7/employees/45/sales 

現在我願意去contacts導航到SalesComponent,但我不知道所有絕對路線的參數(例如上面例子中的部門ID,7)我寧願使用相對鏈接到達那裏,例如

[routerLink]="['../contacts']" 

this.router.navigate('../contacts') 

不幸的是不起作用。可能有一個明顯的解決方案,但我沒有看到它。任何人都可以幫忙嗎?

回答

49

如果您使用的是新的路由器(3.0.0-β2),你可以使用ActivatedRoute導航到相對路徑如下:

constructor(private router: Router, private r:ActivatedRoute) {} 

/// 
goToContact() { 
    this.router.navigate(["../contacts"], { relativeTo: this.r }); 
} 
+0

真棒,作品像一個魅力! –

+0

我實際上處於相同的情況,但它對我無效......自正式發佈以來,有些事情發生了變化? – KCarnaille

+0

@KCarnaille嗯我在@角/路由器3.0.0(完成,而不是測試版),它仍然正常工作。不知道自那以後他們是否有任何突破性變化。 –

29

的RouterLink指令始終把提供的鏈接將作爲delta到當前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}); 
+0

導航爲什麼表現不同? – Kugel