使用Angular 2路由器(版本3)导航相对

Tho*_*ler 50 typescript angular2-routing angular

如何从相对导航/questions/123/step1/questions/123/step2使用分量内Router没有字符串连接和指定/questions/123/

我在下面添加了自己的答案.请随时提出更好的答案.;-)我想有更好的方法.

Tho*_*ler 75

在做了一些研究后,我遇到了

this.router.createUrlTree(['../step2'], {relativeTo: this.activatedRoute});
Run Code Online (Sandbox Code Playgroud)

this.router.navigate(['../step2'], {relativeTo: this.activatedRoute});
Run Code Online (Sandbox Code Playgroud)

第一种方法(Router.createUrlTree API)对我不起作用,即什么也没发生.第二种方法(Router.navigate API)有效.

但是,第二种方法使用NavigationExtras(第二个参数),记录在案@experimental.希望下一个版本再次发生重大变化......并且NavigationExtras会保持稳定.

任何其他建议/方法,请不要犹豫,回答我上面的问题.

更新2016-10-12

还有另一个stackoverflow问题:

更新2016-10-24

文档:


Sha*_*tul 11

首先,在构造函数上注入router&ActivatedRoute

constructor(private route:ActivatedRoute,private router:Router) { }
Run Code Online (Sandbox Code Playgroud)

然后使用Click事件:

onEditClick(){
        this.router.navigate(['edit'],{relativeTo:this.route});
Run Code Online (Sandbox Code Playgroud)

您导航到预期的页面.在我的场景中,我想去recipe/1来编辑配方. HTTP://本地主机:4200 /食谱/ 1 /编辑


Ton*_*ony 5

注意:路由区分大小写,因此请确保匹配大小写

这对 Angular 8 有用:
从父组件/页面,使用打字稿导航到子页面:

this.router.navigate(['subPage'], { relativeTo: this.route });
Run Code Online (Sandbox Code Playgroud)

我的父模块中的路由器如下所示:

const routes: Routes = [
  {
    path: '',
    component: MyPage,
    children: [
      { path: 'subPage', component: subPageComponent}
    ]
  }
];
Run Code Online (Sandbox Code Playgroud)

在父级的 html 页面上,使用以下命令通过链接进行导航:

<a [routerLink]="'subPage'">Sub Page Link</a>
<router-outlet></router-outlet>
Run Code Online (Sandbox Code Playgroud)