首页 > 解决方案 > 嵌套路由 Angular

问题描述

我试图在我的 myfile.routing.module.ts 文件中有两个级别的嵌套路由,但是当我尝试访问该路由时,它会重定向到主目录。这是我的代码:

路由.module.ts

.
.
.
const routes: Routes = [
  {
    path: '',
    children: [
      { path: '', redirectTo: 'home', pathMatch: 'full' },
      {
        path: 'home',
        component: HomeComponent,
        children: [
          { path: '', redirectTo: 'page' },
          {
            path: 'page',
            component: PageComponent,
            canActivate: [PageGuard],
          },
          {
            path: 'more', component: MoreComponent,
            children: [
              { path: '', component: MoreComponent },
              { path: 'plants', component: PlantsComponent },
              { path: 'cars', component: CarsComponent },
              { path: 'pets', component: PetsComponent },
          ]},
        ],
      },
    ],
  },
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule],
})
export class myFileRoutingModule {}

more.component.html我添加了<router-outlet></router-outlet>

home.component.html我有这样的链接:

<a [routerLink]="['home/page/more/plants']">plants</a><br />
<a [routerLink]="['home/page/more/cars']">cars</a><br />
<a [routerLink]="['home/page/more/pets']">pets</a><br />

所以我遇到的问题是我无法访问每个部分(例如主页/页面/更多/植物),因为它一直重定向到主页。

有谁知道是什么问题?

标签: angularangular-routing

解决方案


你不需要第一个空级别,

这可能会解决您的问题:

const routes: Routes = [
    { path: '', redirectTo: 'home', pathMatch: 'full' },
    {
      path: 'home',
      component: HomeComponent,
      children: [
        { path: '', redirectTo: 'page' },
        {
          path: 'page',
          component: PageComponent,
          canActivate: [PageGuard],
        },
        {
          path: 'more', component: MoreComponent,
          children: [
            { path: '', component: MoreComponent },
            { path: 'plants', component: PlantsComponent },
            { path: 'cars', component: CarsComponent },
            { path: 'pets', component: PetsComponent },
        ]},
      ],
    }
];

请注意,所有子组件都必须包含<router-outlet></router-outlet>HomeComponent 和 MoreComponent


推荐阅读