2016-07-28 5 views
29

のは、私はこのルータの設定兄弟のルートに移動するにはどうすればよいですか?

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

と今私はcontactsに行きたいが、私はすべてを持っていないとして、このURL

/department/7/employees/45/sales 

経由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 Hmm私は@ angular/router 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

関連する問題