Home > Mobile >  How to declare routes of feature module as children of another component?
How to declare routes of feature module as children of another component?

Time:06-01

I am refactoring my Angular App. My app-routing.module.ts has two main routes:

const routes: Routes = [
  {path: "login", component: LoginComponent, canActivate: [IsNotLoggedGuard]},
   {path: "", component: MainComponent, canActivate: [AuthGuard],children: [
    {path: "orders", component: OrderComponent, children:[...]
   ]},
  
];

Now, I created a routing module for the newly created OrderModule

// in order-routing.module.ts
const routes = [
    {path: "orders", component: OrderComponent, children:[...]
]

now I could remove the route in app-routing.module.ts

const routes: Routes = [
  {path: "login", component: LoginComponent, canActivate: [IsNotLoggedGuard]},
   {path: "", component: MainComponent, canActivate: [AuthGuard],children: []},
  
];

but in the MainComponent I have a <router-outlet></router-outlet where I want to load all feature components but therefore I have to somehow declare the routes as child routes but how would I do that if I have multiple routing modules for each feature module?

CodePudding user response:

Make use of lazy-loading, these feature modules will be loaded once the user hits a particular route.

app-routing.module.ts

const orderModule = () => import('..../order.module.ts').then(m => m.OrderModule);
const otherFeatureModule = () => import('.../feature1.module').then(m => m.FeatureModule);

const routes: Routes = [
  {
     path: "login", 
     component: LoginComponent, 
     canActivate: [IsNotLoggedGuard]
  },
  {  path: "", 
     component: MainComponent, 
     canActivate: [AuthGuard],
     children: [
       {
         path: 'order', 
         loadChildren: orderModule
       },
       {
         path: 'feature1',
         loadChildren: otherFeatureModule
       }
     ]
  }
];

main-component

<!-- your main content -->
<router-outlet></router-outlet> // here will be displayed 
                                // order and other features 
                                // components

CodePudding user response:

Assuming you have an OrderModule in order.module.ts and inside you import the OrderRoutingModule with the routes defined in order-routing.module.ts

then you could update app-routing.module.ts to lazy load that module like this:

// in order-routing.module.ts
const routes: Routes = [
  {path: "login", component: LoginComponent, canActivate: [IsNotLoggedGuard]},
   {
      path: "", 
      component: MainComponent, 
      canActivate: [AuthGuard],
      loadChildren: () => import('../order/order.module').then((m) => m.OrderModule)
    },
  
];

  • Related