【发布时间】:2018-09-14 15:22:22
【问题描述】:
问题:是否存在定义单页应用程序路由的最佳实践?
在 Angular 项目中,功能通常在延迟加载模块中分离,然后在 AppRoutingModule 和延迟加载模块中配置路由。
假设应用将管理目录,例如:产品。路由可以这样配置:
选项 1:
- 名单:
/products - 创建:
/products/create - 阅读:
/products/:id - 更新:
/products/:id/edit
它可以工作,但看起来有点乱,/products/:id 和/products/create 之间存在一些歧义,因为参数:id 可以匹配字符串“create”。示例代码:
app-routing.module.ts:
const routes: Routes = [
{
path: '',
children: [
{ path: 'products', loadChildren: 'app/products/products.module#ProductsModule' },
]
}
];
products-routing.module.ts
const routes: Routes = [
{ path: '', component: ListProductsComponent },
{ path: 'create', component: CreateProductComponent },
{ path: ':id', component: ViewProductComponent },
{ path: ':id/edit', component: EditProductComponent },
];
选项 2
- 名单:
/products - 创建:
/products/create - 阅读:
/product/:id(注意“产品”是单数) - 更新:
/product/:id/edit(注意“产品”是单数)
没有歧义,但配置变得更乱:
app-routing.module.ts:
const routes: Routes = [
{
path: '',
children: [
// Empty path. It works as long as the ProductsModule has no empty paths. You can define more lazy modules like this.
{ path: '', loadChildren: 'app/products/products.module#ProductsModule' },
]
}
];
products-routing.module.ts
const routes: Routes = [
{ path: 'products', component: ListProductsComponent },
{ path: 'products/create', component: CreateProductComponent },
{ path: 'product/:id', component: ViewProductComponent },
{ path: 'product/:id/edit', component: EditProductComponent },
];
如您所见,在定义路由时,您必须考虑惰性模块的结构和 URL 的“美”。
定义路线的最佳做法是什么,特别是对于 CRUD 操作?有没有好的命名约定?
【问题讨论】:
标签: angular routes angular-cli lazy-loading angular-router