【问题标题】:How to configure Angular module for multiple Child components如何为多个子组件配置 Angular 模块
【发布时间】:2021-12-27 19:05:31
【问题描述】:

在我的 Angular 项目中,我需要为 Admin 创建一个单独的部分并将所有组件保留在那里...现在我为此创建了一个单独的模块但无法根据路由呈现组件...

我的代码:组件

  1. 管理员配置文件组件
  2. 管理员订阅组件

现在在模块上... 创建管理模块和routing.module.ts。

 const routes: Routes = [
  { path: '/profile', component: ProfileComponent },
  { path: '/subscription', component: SubscriptionComponent },
];

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

现在在 app.module.ts 我将路由配置为:

path: 'admin',
    loadChildren: () =>
      import('./modules/admin/admin.module').then(
        (m) => m.adminModule
      ),
    canActivate: [AuthGuard],

我想要的结果:

url: admin/profile => load profile component
url: admin/subscription => load subscription component.

请指导。

【问题讨论】:

  • 为什么不为profilesubscription 创建一个单独的模块?
  • @Roy 我们将来可能会有几个组件

标签: angular angular-module


【解决方案1】:

您可以在您的应用路由主文件中添加管理路由并添加它们的模块,如下所示:

app-routing.module.ts

...
{
    path: 'admin',
    loadChildren: 'app/modules/admin/admin.module#AdminModule',
    canActivate: [AuthGuard],
    canActivateChild: [AuthGuard], // Add this if you have authguard for child routes as well.
}
...

admin.routing.module.ts

...
{
    path: '',
    component: LayoutComponent,
    children: [
        { path: '', redirectTo: 'profile', pathMatch: 'full' },
        { path: 'profile', component: ProfileComponent },
        { path: 'subscription', component: SubscriptionComponent },
        { path: '**', redirectTo: '' }
    ]
}
...

LayoutComponent.html

<main>
<router-outlet></router-outlet>
</main>

我希望你明白这一点,如果没有,请评论你的问题;很乐意帮忙。

【讨论】:

  • 感谢您的支持。按预期工作:)。非常感谢。
猜你喜欢
  • 1970-01-01
  • 2018-04-28
  • 1970-01-01
  • 2017-01-27
  • 2022-07-06
  • 1970-01-01
  • 1970-01-01
  • 2014-11-17
  • 2016-05-21
相关资源
最近更新 更多