Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
142 views
in Technique[技术] by (71.8m points)

Nested routes Angular

I am trying to have two levels of nested routes in my myfile.routing.module.ts file but when I try to access to the route it redirects to the home. Here is my code:

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 {}

in more.component.html I have added <router-outlet></router-outlet>

and in home.component.html I have the links like so:

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

so the problem that I have is that I can't access to each section (for example home/page/more/plants) because it redirects to home all time.

Does anyone know what's the problem?

question from:https://stackoverflow.com/questions/65942513/nested-routes-angular

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You don't need the first empty level,

This might fix your problem:

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 },
        ]},
      ],
    }
];

Notice all component that came with children must contain <router-outlet></router-outlet> like HomeComponent & MoreComponent


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...