要在Angular 8中使用嵌套路由和子模块,您需要按照以下步骤进行设置:
app.module.ts
的文件。import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
const routes: Routes = [
{ path: '', redirectTo: '/home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent },
{ path: 'products', component: ProductsComponent, children: [
{ path: 'list', component: ProductListComponent },
{ path: 'details/:id', component: ProductDetailsComponent }
]},
{ path: '**', component: PageNotFoundComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
products.module.ts
的文件。import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule, Routes } from '@angular/router';
import { ProductsComponent } from './products.component';
import { ProductListComponent } from './product-list.component';
import { ProductDetailsComponent } from './product-details.component';
const routes: Routes = [
{ path: '', component: ProductsComponent, children: [
{ path: 'list', component: ProductListComponent },
{ path: 'details/:id', component: ProductDetailsComponent }
]}
];
@NgModule({
declarations: [
ProductsComponent,
ProductListComponent,
ProductDetailsComponent
],
imports: [
CommonModule,
RouterModule.forChild(routes)
],
exports: [
RouterModule
]
})
export class ProductsModule { }
app.module.ts
中添加以下导入语句和imports
数组:import { ProductsModule } from './products/products.module';
@NgModule({
imports: [
// ...
ProductsModule
],
// ...
})
export class AppModule { }
标签,以便在路由切换时显示正确的组件。例如,在app.component.html
中:My App
请注意,上述代码示例假设您已经创建了相应的组件(HomeComponent
、ProductsComponent
等),并且已经将它们添加到主模块和子模块的声明数组中。
如果您遵循了以上步骤,但嵌套路由仍然不起作用,请确保您的路由路径和组件名称正确,并且没有其他冲突或错误。同时,还可以检查浏览器的开发者工具中的控制台,以查看是否有任何路由相关的错误信息。