簡體   English   中英

如何正確設置角度嵌套路由

[英]How to properly setup nested routing in angular

我正在嘗試使用嵌套路徑設置角度路線。 父頁面是/list子頁面是/list/:id

出於某種原因,以下路線不起作用。 如果我導航到/list/:id ,會找到路由,但它會加載ListComponent而不是ViewComponent

{
  path: 'list',
  component: ListComponent,
  children: [
    {
      path: ':id',
      component: ViewComponent
    }
  ]
}

我很確定這與angular doc 中的示例設置相同。 我錯過了什么嗎?

以下有效,但它的層次結構錯誤, /list/list/:id兄弟

{
  path: 'list',
  children: [
    {
      path: '',
      component: ListComponent
    },
    {
      path: ':id',
      component: ViewComponent
    }
  ]
}

參見stackblitz 示例

在第一個示例中,由於 ViewComponent 是 ListComponent 的子項,因此您必須根據您的 stackblitz 示例在 list.component.html 中添加<router-outlet></router-outlet>

<p>
list works!
</p>

<a [routerLink]="['./view']">view</a>
or 
<button (click)="buttonClick()">view</button>

<!-- add the line below here-->
<router-outlet></router-outlet>

ViewComponent 被加載到你放置路由器插座的地方。

當您轉到路由 /list/:id 時,這將使 Angular 加載 ListComponent 和 ViewComponent,因為 ViewComponent 是 ListComponent 的子項。

每條有孩子的路線,都需要有<router-outlet></router-outlet>標簽。

例如,如果 ListComponent 是導航側欄,並且 ViewComponent 包含來自后端的數據,則此架構很有用(以及許多其他類型的情況)。

編輯

如果您不想在訪問 /list/:id 路由時同時加載 ListComponent 和 ViewComponent,則可以將路由更改為如下所示:

const mainRoutes: Routes = [
  {
    path: 'list',
    component: ListComponent,
  },
  {
    path: 'list/:id',
    component: ViewComponent
  }
];

當您使用此架構時,僅在您訪問“list/:id”時加載 ViewComponent,因為 ViewComponent 不是 ListComponent 的子項。

在這個例子中,你不應該在 list.component.html 中使用 router-outlet

由於 ViewComponent 是一個子組件,您必須在父組件中渲染它。 您可以通過在 ListComponent 中添加<router-outlet></router-outlet>來實現。 它會解決你的問題。

以前,在一個項目中,我是通過以下方式完成的(我更改了組件的名稱以匹配您的組件):

const routes: Routes = [
{
  path     : 'list',
  component: ListComponent      
},
{
  path     : 'list/:id',
  component: ViewComponent      
},
  {
    path     : '**',
    component: ListComponent        
  }  
];

然后在進口中:

@ngModule({
    imports: [RouterModule.forChild(routes)]
})

希望有幫助。

暫無
暫無

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

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