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

问题描述 投票:44回答:3

如何使用/questions/123/step1在没有字符串连接并指定/questions/123/step2的情况下从组件中的Router导航到/questions/123/

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

angular typescript angular2-routing
3个回答
66
投票

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

this.router.createUrlTree(['../step2'], {relativeTo: this.activatedRoute});

this.router.navigate(['../step2'], {relativeTo: this.activatedRoute});

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

然而,第二种方法使用NavigationExtras(第二个参数)与@experimental记录。希望下一个版本再次发生重大改变......而NavigationExtras将保持稳定。

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

更新2016-10-12

还有另一个stackoverflow问题:

更新2016-10-24

文档:

更新2019-03-08

似乎Angular 7.1有变化。在另一篇文章中有一个答案如何使用Angular 7.1解决它。请参考https://stackoverflow.com/a/38634440/42659


8
投票

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

constructor(private route:ActivatedRoute,private router:Router) { }

然后使用Click事件:

onEditClick(){
        this.router.navigate(['edit'],{relativeTo:this.route});

您导航到预期的页面。在我的方案中,我想去recipe / 1来编辑配方。 http://localhost:4200/recipes/1/edit


1
投票

你可以在下面使用,

假设是questions加载到您的主要router-outlet

  this.router.navigate([
      '/',
      { 
        outlets: {
          primary: [
              // below may be replaced with different variables
              'questions',
              '123',  
              'step2'
          ]
        }
      }
  ])

希望这可以帮助!!

© www.soinside.com 2019 - 2024. All rights reserved.