【发布时间】:2021-12-19 22:36:01
【问题描述】:
我想知道如何在我的应用程序中正确地咬住路由主题。
现在的样子: app-routing.module.ts 文件:
const routes: Routes = [
{
path: '',
component: MainLayoutComponent,
children: [
{
path: '',
loadChildren: '../app/modules/home.module#HomeModule'
},
{
path: '',
loadChildren: '../app/modules/products.module#ProductsModule'
}
]
},
{
path: '**',
redirectTo: '/404'
}
];
我知道它看起来很糟糕。两条相同的路径:''。 但在 ProductsModule 我的路由看起来像这样:
products.routing.ts 文件:
const routes: Routes = [
{
path: 'products/:id',
component: ProductDetailsComponent
},
{
path: ':mainCategory',
component: ProductsComponent
},
{
path: ':mainCategory/:subCategory',
component: ProductsComponent
}
];
我想做什么:
1. 转到:'/products/12331' 后,加载 ID 为 12331 的 ProductDetailsComponent。
可能它不起作用,因为主模块有路径:''。
将ProductDetailsComponent与ProductsComponent分开是解决这个问题的方法吗?
这样我的 app-routing.module.ts 会看起来:
const routes: Routes = [
{
path: '',
component: MainLayoutComponent,
children: [
{
path: '',
loadChildren: '../app/modules/home.module#HomeModule'
},
{
path: 'products',
loadChildren: '../app/modules/products.module#ProductsModule'
},
{
path: ':mainCategoryId',
loadChildren: '../app/modules/products.module#CategoriesModule' (adding new module with CategoriesComponent)
}
]
},
{
path: '**',
redirectTo: '/404'
}
];
第二个问题是我正在从后端加载类别。 如何解决路由到不存在的类别的问题? 例如我有类别:
- 食品 [饮料、肉类、披萨]
- 衣服 [鞋子、夹克、帽子]
现在如果我要去:
/Foods/Drinks - 应该加载 CategoriesComponent
/Foods/Shoes - 应该路由到 /404 但如何处理呢? (类别不存在)
/randomName/Drinks - 应该路由到 /404
我该如何解决?也许我的问题很愚蠢,但我正在学习角度:)
【问题讨论】:
标签: angular typescript routes frontend components