mario
mario

Reputation: 206

Angular 11 problem with loadChildren in routing

After I log in into my app I go to the link

this.router.navigate(['/sellTicket/chooseTicket']);

In my app-routing I have following:

const routes: Routes = [
  {path: 'login', component: LoginComponent},
  {path: '', canActivate: [AuthGuard], component: HomeComponent, children: [ //todo w AuthGuard trzeba sprawdzic, czy dane logowania poprawne
      {path: 'sellTicket', loadChildren: () => import('./sell-ticket/sell-ticket.module').then(m => m.SellTicketModule)},
    ]},
  {path: '**', component: PageNotFoundComponent}
];

@NgModule({
  imports: [RouterModule.forRoot(routes, {enableTracing: false, useHash: true})],
  exports: [RouterModule]
})
export class AppRoutingModule { }

I can see that the Home component is initialized because of the console.log I've put, but, the SellTicketComponent is not. Inside the home.component.html I have

<app-header></app-header>
<br>
<br>
<br>
<router-outlet></router-outlet>

I'm not sure what is the problem here. In my sell-ticket-routing.module I have

const ticketRoutes: Routes = [
    {path: '', component: SellTicketComponent, children: [
            {path: 'chooseTicket', component:ChooseTicketComponent},
            {path: 'chooseTrain', component:ChooseTrainComponent}
        ]}
]

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

so if the path starts with sellTicket it should load the SellTicketComponent, and then if the folowing path matches it should load propr component as well but it doesnt

Upvotes: 1

Views: 4779

Answers (2)

SaiSurya
SaiSurya

Reputation: 1116

Hello I made few changes to the code you posted in stackbliz it is working fine please check if that is what you need or revert back so that I can help you better.

Changes made are added declarations in sell ticket module, Corrected selector used in index.html with the selector in app.component.ts and Modified routing in app module and also added direct routing in sell ticket module.ts file without separate file.

Username: user
Password: test

Link: https://stackblitz.com/edit/angular-ivy-pp7r11?file=src%2Fapp%2Flogin%2Flogin.component.ts

Upvotes: 2

devj
devj

Reputation: 387

In your app-routing.module change ticketRoutes in:

const routes: Routes = [
  {
    path: '',
    redirectTo: 'home',
    pathMatch: 'full',
  },
  {
    path: 'home',
    component: HomeComponent,
    canActivate: [AuthGuard],
  },
      {path: 'ticket',
      loadChildren: () =>import('./sell-ticket/sell-ticket.module').then(m => m.SellTicketModule)},

  {path: '**', component: PageNotFoundComponent}
];
And in sell-ticket-module:

const ticketRoutes: Routes = [
  {path: '', component: SellTicketComponent},
  {path: 'chooseTicket', component:ChooseTicketComponent},
  {path: 'chooseTrain', component:ChooseTrainComponent}
]

Upvotes: 0

Related Questions