在 Angular 6 中将路由拆分为单独的模块

tha*_*dam 3 javascript routes typescript angular

我正在开发 Angular 6 应用程序。目前我正在为路由而苦苦挣扎。我感兴趣的是,我的结构,我想象的是否可行。所以它看起来像这样:

应用程序模块 - 包含主路由和一些父路由,其中​​定义了布局。像这样:

const routes: Routes = [
{
    path: 'login',
    component: LoginComponent
},
{
    path: '',
    component: LayoutComponent,
    canActivate: [AuthGuard],
    canActivateChild: [AuthGuard],
    children: [
    // {
    //   path: 'brands',
    //   loadChildren: 'app/modules/brands/brands.module#BrandsModule',
    //   pathMatch: 'prefix'
    // }
    ]
}
];

@NgModule({
    imports: [RouterModule.forRoot(routes), BrandsModule, ItemsModule],
    exports: [RouterModule],
    providers: [BosRouteLoader]
})
export class RoutingModule {}
Run Code Online (Sandbox Code Playgroud)

我的一个功能模块在模块中定义了自己的路由,如下所示:

const routes: Routes = [
{
    path: 'brands',
    children: [
    { path: '', component: BrandListComponent },
    { path: ':id', component: BrandDetailComponent },
    { path: '**', redirectTo: '' }
    ]
}];


@NgModule({
    imports: [RouterModule.forChild(routes)],
    exports: [RouterModule]
})
export class BrandsRoutingModule {}
Run Code Online (Sandbox Code Playgroud)

我希望实现每个功能模块都定义自己的路由,并将这些路由注册为应用程序模块的子路由。

通过延迟加载,我可以管理它,但随后我必须始终在我的应用程序模块中定义另一条路线,但我只想在功能模块中定义它。

如果我在没有延迟加载的情况下执行此操作,那么应用程序组件中的我的父路由永远不会被命中。因此,如果我访问http://localhost/brands ,它将加载适当的 BrandLisComponent 但不加载 LayoutComponent。

有没有办法在功能模块中定义路由并将它们注册为主路由模块的子模块?

ima*_*s77 5

这个概念是,您在更高级别的模块中定义模块路由,然后在所需的模块中定义其子级。

因此,就您而言,您需要告诉角度,嘿,当有人去brands路线时,请使用BrandsRoutingModule路线。

因此,在您的应用程序模块中,您将拥有:

{
    path: 'brands',
    loadChildren: 'app/modules/brands/brands.module#BrandsModule',
    canActivate: [AuthGuard],
    canActivateChild: [AuthGuard],
}
Run Code Online (Sandbox Code Playgroud)

这表明如果用户转到 ,您需要加载该模块的路由/brand

然后在您的 中BrandsRoutingModule,您需要将路由定义为:

{
    path: '',
    component: LayoutComponent,
    children: [
        { path: '', redirectTo: 'home', pathMatch: 'full' },
        { path: 'home', component: BrandListComponent },
        { path: ':id', component: BrandDetailComponent },
        { path: '**', redirectTo: '' }
    ]
}
Run Code Online (Sandbox Code Playgroud)

因此,每当我们路由到 时/brands,我们都会将 视为相LayoutComponent对于该的主要路由,然后BrandListComponent和其他路由将作为他的子路由。但为了向他的孩子们展示,您还需要将这行代码放入您的layout.component.html

<router-outlet></router-outlet>
Run Code Online (Sandbox Code Playgroud)

这告诉 Angular,嘿,如果他要这样做/brands/2,你需要加载内部BrandDetailComponent LayoutComponent字面上作为他的孩子。

希望能帮助到你。