簡體   English   中英

使用 Angular 2 路由器(版本 3)進行相對導航

[英]Navigate relative with Angular 2 Router (Version 3)

如何使用Router在組件內從/questions/123/step1相對導航到/questions/123/step2而不使用字符串連接並指定/questions/123/

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

在做了一些更多的研究之后,我遇到了

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

首先,在構造函數上注入 router & ActivatedRoute

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

然后使用單擊事件:

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

您導航到預期頁面。在我的場景中,我想轉到 recipe /1 來編輯該 recipe。 http://localhost:4200/recipes/1/edit

注意:路線區分大小寫,因此請確保匹配大小寫

這對我來說適用於 Angular 8:
從父組件/頁面,使用打字稿導航到子頁面:

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

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

const routes: Routes = [
  {
    path: '',
    component: MyPage,
    children: [
      { path: 'subPage', component: subPageComponent}
    ]
  }
];

並在父級的 html 頁面上使用以下內容使用鏈接進行導航:

<a [routerLink]="'subPage'">Sub Page Link</a>
<router-outlet></router-outlet>

您可以在下面使用,

假設questions已加載到您的主要router-outlet

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

希望這有幫助!!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM