2016-12-30 92 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