如何正确设置角度嵌套路由

时间:2021-07-30 07:24:21

标签: 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 example

3 个答案:

答案 0 :(得分:1)

在第一个示例中,由于 ViewComponent 是 ListComponent 的子项,因此您必须根据您的 stackblitz 示例在 list.component.html 中添加 mat <- matrix(data = NA, nrow = 10, ncol = 10, byrow = FALSE, dimnames = NULL) i <- 0 for(p in seq(0, 0.018, by = 0.002)){ i <- i+1 j <- 0 for(k in seq(2, 20, by =2)){ j <- j+1 mat[i,j] <- find.cor(p,k) # print(find.cor(p,k)) } }

<router-outlet></router-outlet>

ViewComponent 在此处加载,您放置路由器插座的位置。

当您转到路由 /list/:id 时,这将使 Angular 加载 ListComponent 和 ViewComponent,因为 ViewComponent 是 ListComponent 的子项。

每条有孩子的路线都需要有 <p> list works! </p> <a [routerLink]="['./view']">view</a> or <button (click)="buttonClick()">view</button> <!-- add the line below here--> <router-outlet></router-outlet> 标签。

例如,如果 ListComponent 是导航侧边栏,并且 ViewComponent 包含来自后端的数据,则此架构很有用(以及许多其他类型的情况)。

编辑

如果您不想在访问 /list/:id 路由时同时加载 ListComponent 和 ViewComponent,则可以将路由更改为如下所示:

<router-outlet></router-outlet>

当你使用这种架构时,只有当你访问“list/:id”时才会加载 ViewComponent,因为 ViewComponent 不是 ListComponent 的子项。

在这个例子中,你不应该在 list.component.html 中使用 router-outlet

答案 1 :(得分:0)

因为 ViewComponent 是一个子组件,你必须在父组件内部渲染它。您可以通过在 ListComponent 中添加 <router-outlet></router-outlet> 来实现。它将解决您的问题。

答案 2 :(得分:-1)

之前,在一个项目中,我是通过以下方式完成的(我更改了组件的名称以匹配您的组件):

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

然后在导入中:

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

希望有所帮助。