簡體   English   中英

Angular2 this.router.navigate僅觸發一次

[英]Angular2 this.router.navigate fires only once

我的頁面中具有以下標簽結構,並在花括號中給出了相應的URL:

           Main Tab (/page)
           /    |    \
          /     |     \
         /      |      \
        /       |       \
Sub Tab 1   Sub Tab 2   Sub Tab 3
(/page/a)   (/page/b)   (/page/c)

零件

@Input() route: string = '';

selectTab(tab) {
  let route = this.router.url.split('?')[0];

  /* Here redirectUrl = "/page/c" */
  if (tab.redirectUrl.length > 0) {
    // console.log(tab.redirectUr); gives /page/c

    this.router.navigate([tab.redirectUrl]);
    // This works but reloads the page and is a very bad idea.
    // window.location.href = tab.redirectUrl;
  }
}

Component.html

注意:實際代碼中有一個自定義元素,我將其顯示為<div>只是為了展示如何傳遞redirectUrl

<div route="/page" [redirectUrl]="/page/c"></div>

當我單擊Main Tab時,將調用selectTab函數。 並且由於Main選項卡具有redirectUrl因此if條件滿足並且頁面從/page/page/c 這只能工作一次

但是,如果我單擊任何其他“ 子選項卡” (例如具有URL /page/b Sub Tab 2 ),則單擊主選項卡不會重定向到/page/c ,而是停留在/page/b

我已經檢查了如果條件中的redirectUrl ,它仍然是/page/c ,但是不會發生重定向。

我應該怎么做才能強制重定向?

編輯

@HuseinRoncevic

<div *ngFor="let tab of tabs" (click)="selectTab(tab)">

編輯

路線

{
  path: 'page',
  component: MyComponent
},
{
  path: 'page/:action',
  component: MyComponent
}

您可以嘗試以下方法:

{ path: 'page', component: PageParentComponent,
        children: [
          { path: '', redirectTo: 'a', pathMatch: 'full'},
          { path: 'a', component: AComponent},
          { path: 'b', component: BComponent}
        ]
 }

在HTML中

this.router.navigate(['page/a']); // or
this.router.navigate(['page/b']);

我不確定為什么您的路線定義指向相同的組件:

{
    path: 'page',
    component: MyComponent
},
{
    path: 'page/:action',
    component: MyComponent
}

為什么不為page/:action路線創建單獨的組件?

這是Angular.io上的“ 路由和導航”文檔中的內容。

可觀察的paramMap和組件重用在此示例中,您從一個可觀察的對象檢索路徑參數映射。 這意味着路由參數圖可以在該組件的生命周期內更改。

他們可能。 默認情況下,路由器在重新導航到相同組件類型時會重用組件實例,而無需先訪問其他組件。 路線參數可能會每次更改。

我相信這是您的問題。 您並沒有真正在更改組件。 而是一次又一次地重復使用相同的組件。 因此,路由器重用了相同的組件實例。

因此,我將創建一個新組件來處理路由的:action部分。

{
    path: 'page',
    component: MyComponent
},
{
    path: 'page/:action',
    component: IHandleActionPartHereComponent
}

更新資料

在您的selectTab()函數中,沿問號分割的目的是什么?

let route = this.router.url.split('?')[0];

您的路線不會作為查詢參數附加,而是會像http://something/page/a而不是http://something/?page/b一樣附加到實際路線,或者您會想到。 url屬性將返回路由器確定的url: /page/a/page/b 結果的長度應為0。因此,您的if部分將始終為false,並且不會發生重定向。

暫無
暫無

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

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