在Angular 2中导航子路由

11

我似乎无法在子路由之间导航。

路由器概述:

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 });

但我不断收到错误提示:无法匹配任何路由。 URL 段:'new/asset'。

如果我手动插入 URL,它就可以正常工作。

非常感谢您的帮助!

3个回答

16

你可以使用../

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

这个有效,谢谢!我遇到了很多问题的原因是我在服务中使用了导航操作而不是组件本身。 - David Pascoal
1
我明白了。relativeTo路由在服务中不太容易获取。 - Günter Zöchbauer

7
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>

第二个路径应该以 / 开头。即使需要将 relativeTo 视为相对路径,我也会在路径前加上 / 以使其更明显。 - Günter Zöchbauer
1
@GünterZöchbauer,它也可以不带/工作,但为了更清晰,我添加了斜杠。 - Milad

3

当您使用relativeTo并尝试导航时,应该输入相对路径,而不仅仅是从父级视角下的整个路径。在您的示例中,应该更像这样:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接