如何在角度7中创建可选的路由器参数

时间:2019-03-21 19:18:09

标签: angular typescript angular-router

我的路由器配置如下所示。

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
  }
];

反正还是有角度的,而没有复制我可以实现的完整路由配置。

意味着我可以将参数指定为可选参数吗?

2 个答案:

答案 0 :(得分:0)

有一种方法(我没有测试) 如果您制作一个模块,并在该模块布线中添加以下项目

  { 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 }

答案 1 :(得分:0)

我不知道使参数可选的方法。根据您要实现的目标,可以使用可以在id参数中检测到的特定字符串(Registration / new与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 }
]