How to dynamically add routes to a lazyloaded Module?

71 views Asked by At

The route configuration of a lazy-loaded module is structured differently because lazy-loaded modules have their own separate route configurations. In my case, I have routes fetched from the database and need to apply them to the router.config when the user successfully logs in.

the core module is lazyloaded in the app module on path 'core'.

app-routing.modules.ts

const routes: Routes = [
  { path: '', redirectTo: '/login', pathMatch: 'full' },
  { path: 'login', component: LoginComponent },
  { path: 'core', loadChildren: () => import('@modules/pu-core/pu-core.module').then(m => m.PuCoreModule) }
];

Core module

const routes: Routes = [
  { path: 'layout', component: LayoutComponent, childre:[] },
];

on the success of login, the auth service has an observable apiRoutes$ that holds the routes that needs to be applied to the layout path children.

Using of this.router.config to dynamically add the children doesn't work since the config is different.

The below implementation doesn't work:

constructor(public router: Router, private activatedRoute: ActivatedRoute, @SkipSelf() private auth: AuthService) {

    this.auth.routes$.subscribe(
      (routesData: any) => {
        this.router.config[2].children = routesData;
      }
    )
  }
1

There are 1 answers

1
Pablo Depiné On
  • Updating Routes After Login: After successful login, you can inject PuCoreRoutingService into your authentication service (or wherever you are handling login success) and update the routes as needed.
constructor(private puCoreRoutingService: PuCoreRoutingService) {}

onLoginSuccess(): void {
  this.auth.routes$.subscribe((routesData: Routes) => {
    this.puCoreRoutingService.updateLayoutChildrenRoutes(routesData);
  });
}
  • Route Update Service in Core Module: Create a service within the PuCoreModule that allows updating routes. This service can have a method to update the child routes of the LayoutComponent.
import { Injectable } from '@angular/core';
import { Router, Routes } from '@angular/router';

@Injectable({
  providedIn: 'root'
})
export class PuCoreRoutingService {
  constructor(private router: Router) {}

  public updateLayoutChildrenRoutes(routes: Routes): void {
    const config = this.router.config;
    const layoutRoute = config.find(r => r.path === 'layout');
    if (layoutRoute) {
      layoutRoute.children = routes;
      this.router.resetConfig(config);
    }
  }
}