簡體   English   中英

如何以角度動態配置路由

[英]how to dynamically configure routes in angular

我有一個angular 13應用程序並且需要配置路線。 但是,我有大量的路線,它們的模式不同,如下所示

const routes: Routes = [
    {
      path: 'applicant/info',
      component: ApplicantComponent,
      children: [
        {
          path: 'section-a',
          component: SectionAComponent,
          canActivate: [AuthGuard],
        },
        {
            path: 'section-b',
            component: SectionBComponent,
            canActivate: [AuthGuard],
          },
          {
            path: 'section-c',
            component: SectionCComponent,
            canActivate: [AuthGuard],
          },
          //d,e,f,g & so on...
         ]
        }]

這些部分的設計和內容非常不同,所以我必須創建很多組件

但是這些路線配置變得混亂,但我認為這可以簡化

為此,我嘗試了類似下面的方法

const configureRoutes = () => {
const sections = ['A', 'B', 'C'] //& so on a to z
const appRoutes = [];
for(const section of sections) {
 appRoutes.push({
            path: 'section-'+section.toLowercase(),
            component: `Section${section}Component`,
            canActivate: [AuthGuard],
          })
}
return appRoutes;
}

& 然后在主路由配置中,我可以使用此功能,如下所示

    const routes: Routes = [
    {
      path: 'applicant/info',
      component: ApplicantComponent,
      children:configureRoutes()
    }

但是,這不會構建並引發多個編譯時錯誤?

如何以我嘗試的預期方式配置路由?

謝謝!

您可以使用對象的配置數組

您當前的方法是嘗試使用字符串來表示組件,但它必須是對類本身的實際引用

const sections = [
  {
     path: 'section-a',
     component: SectionAComponent,
  }
   ...
]

// then map the above array additing the canActivate AuthGuard

雖然沒有比普通路線好多少

選擇

如果您為每個組件添加了一個靜態字符串屬性,並將其設置為所需的path ,則可以循環/映射該數組以構建一個路由數組

const routes = [SectionAComponent, SectionBComponent...].map(
    component => ({
      component,
      path: component.path
    })
  )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM