2016-12-30 64 views
6

我似乎無法在子路線之間導航。兒童路線之間的導航Angular 2

路由器概述:

path: 'parent', component: parentComponent, 
     children: [ 
      { path: '', redirectTo: 'child1', pathMatch: 'full' }, 
      { path: 'child1', component: child1Component }, 
      { path: 'child2', component: child2Component }, 
      { path: 'new/:type', component: child3Component }, 

      { path: '**', component: PageNotFoundComponent } 
     ] 

我在的child1組件試圖導航到新/型路線,像這樣:

this._router.navigate(['new', objType], { relativeTo: this._route }); 

但我不斷收到錯誤:無法匹配任何路線。網址細分:「新/資產」。

如果我手動插入網址,它工作正常。

幫助將不勝感激,謝謝!

回答

11

您可以使用../

this._router.navigate(['../new', objType], { relativeTo: this._route }); 
+0

這工作,謝謝!我有這麼多問題的原因是因爲我在服務中使用導航操作,而不是組件本身。 –

+1

我明白了。 relativeTo路由不太容易進入服務。 –

3

當您使用relativeTo,然後嘗試導航,你應該把在相對路徑,不只是從父母的角度來看整個之一。在你的榜樣應該是更喜歡:

this._router.navigate([ '../', objType ], { relativeTo: this._route }); 
4
this.router.navigate(['../../new'], { relativeTo: this._route }) 

或者

this.router.navigate(['/parent/new']) 

或用錨標記:

<a [routerLink]=" ['../../new'] "> 
     Go to new 
</a> 

或者:

<a [routerLink]=" ['/parent/new'] "> 
     Go to new 
</a> 
+0

不應該以'/'開頭。儘管它需要'relativeTo'作爲相對路徑來對待,我還是用'/'作爲前綴來使其更加明顯。 –

+1

@GünterZöchbauer,它的工作沒有/,但要更清楚,我加了斜槓 – Milad