Angular 11 路由中loadChildren的问题

Angular 11 problem with loadChildren in routing

登录我的应用程序后,我转到 link

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

在我的应用程序路由中,我有以下内容:

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

我可以看到 Home 组件已初始化,因为我输入了 console.log,但 SellTicketComponent 未初始化。在 home.component.html 我有

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

我不确定这里有什么问题。在我的销售单中-routing.module 我有

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

因此,如果路径以 sellTicket 开头,它应该加载 SellTicketComponent,然后如果以下路径匹配,它也应该加载 propr 组件,但它不会

在您的应用中-routing.module 更改 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}
];
在售票模块中:

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

您好,我对您在 stackbliz 中发布的代码进行了一些更改,它工作正常,请检查这是否是您需要的,或者恢复原样,以便我可以更好地帮助您。

所做的更改是在售票模块中添加了声明,更正了 index.html 中使用的选择器与 app.component.ts 中的选择器以及修改了应用程序模块中的路由,还在售票中添加了直接路由 module.ts 没有单独文件的文件。

用户名:用户
密码:test

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