2016-07-28 2 views
29

하자 가정 나는이 라우터 설정형제 경로를 탐색하려면 어떻게해야합니까?

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

있어이 URL 이제

/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

@KCailaille 흠 @ 각도/라우터 3.0.0 (완료, 베타가 아님)에 있지만 제대로 작동합니다. 그 이후로 큰 변화가 있는지 확실하지 않습니다. –

29

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" 

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

관련 문제