如何在angular 7中创建可选路由器参数
我的路由器配置如下所示如何在angular 7中创建可选路由器参数,angular,typescript,angular-router,Angular,Typescript,Angular Router,我的路由器配置如下所示 const routes: Routes = [ { path: 'Registration', component: RegisterComponent, children: [ { path:'',component:ProfileComponent}, { path: 'Dependent', component: DependentComponent }, { path: 'Matrimony', c
const routes: Routes = [
{
path: 'Registration',
component: RegisterComponent,
children: [
{ path:'',component:ProfileComponent},
{ path: 'Dependent', component: DependentComponent },
{ path: 'Matrimony', component: MatrimonyComponent },
{ path: 'Subscription', component: MagazinesubscriptionComponent },
{ path: 'Donation', component: DonationComponent }
]
},
{
path: 'Profile',
component: ProfilelistComponent
//component: VoteprofileComponent
}
];
这就是我想用来编辑的路由器。意思如下所示
const routes: Routes = [
{
path: 'Registration/:id',
component: RegisterComponent,
children: [
{ path:'',component:ProfileComponent},
{ path: 'Dependent', component: DependentComponent },
{ path: 'Matrimony', component: MatrimonyComponent },
{ path: 'Subscription', component: MagazinesubscriptionComponent },
{ path: 'Donation', component: DonationComponent }
]
},
{
path: 'Profile',
component: ProfilelistComponent
//component: VoteprofileComponent
}
];
在angular中是否存在任何问题,而无需复制我可以实现的完整路由配置
是否可以将参数指定为可选参数?有一种方法(我没有测试它)
如果制作一个模块,请在该模块中添加以下项目
{ path:'',component:ProfileComponent},
{ path: 'Dependent', component: DependentComponent },
{ path: 'Matrimony', component: MatrimonyComponent },
{ path: 'Subscription', component: MagazinesubscriptionComponent },
{ path: 'Donation', component: DonationComponent }
然后你可以在app.routing中重复使用它
{ path: 'Registration', loadChildren: 'pathToYourModule#ModuleName' },
{ path: 'Registration/:id', loadChildren: 'pathToYourModule#ModuleName' },
{ path: 'Profile', component: ProfilelistComponent }
我不知道如何使参数成为可选的。根据您试图实现的目标,您可以使用在id参数中检测到的特定字符串(Registration/new vs Registration/678A6) 无论如何,这些路线只是简单的打字脚本,所以我想你可以这样保持干燥:
const registrationRouteConfig = {
component: RegisterComponent,
children: [
{ path:'',component:ProfileComponent},
{ path: 'Dependent', component: DependentComponent },
{ path: 'Matrimony', component: MatrimonyComponent },
{ path: 'Subscription', component: MagazinesubscriptionComponent },
{ path: 'Donation', component: DonationComponent }
]
}
const routes: Routes = [
{ path: 'Registration', ...registrationRouteConfig },
{ path: 'Registration/:id', ...registrationRouteConfig },
{ path: 'Profile', component: ProfilelistComponent }
]
您必须指定路由,否则angular将无法知道路由到何处。您的第二个路由配置看起来很奇怪。@penleychan感谢您的回复,是的,只是一个复制粘贴问题。我纠正了它。我可以在不复制子路由的情况下执行此操作。通过某种方式,我可以将:Id设置为optional。我使用了此答案中描述的技术:使用和不使用“optional”route参数定义路由。在组件的ngOnInit()中,我将参数值提取到字段中。在视图中,我检查该字段是否存在未定义的内容,并决定将其视为“默认”值。