简体   繁体   中英

how to dynamically configure routes in angular

I have an angular 13 app & need to configure routes. However I have huge number of routes which have vary similar pattern as below

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

The design & content of these sections is very different so I have to create that many components

But these routes configuration is getting messy but I think this could be simplified

To do so, I was trying something like below

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

& then in the main routes configuration, I could use this function as trying below

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

However, this doesn't build & throwing multiple compile time errors?

How can I configure the routes in the intended way of my trying?

Thanks!

You could use a config array of objects

Your current approach is attempting to use strings to represent the components, but it has to be an actual reference to the class itself

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

// then map the above array additing the canActivate AuthGuard

Not much better that the plain route approach though

Alternative

If you added a static string property to each component, and set it to the desired path , you could loop through/map that array to build an array of routes

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM