嵌套路由 Angular

时间:2021-01-28 17:45:46

标签: angular angular-routing

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

routing.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 />

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

有人知道这是什么问题吗?

1 个答案:

答案 0 :(得分:2)

你不需要第一个空层,

这可能会解决您的问题:

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

相关问题