DEV Community

Krijesh
Krijesh

Posted on

Angular Complex Dynamic Routing!

Angular’s flexibility truly shines in complex scenarios!Woow!!! Recently, I encountered a particularly intricate situation while working on dynamic routing in Angular.

Picture this: Launch your Angular application at http://localhost:4200/mydomain, and here, ‘mydomain’ comes dynamically from an event listener. Sometimes, you might even receive both a main domain and a subdomain, requiring your Angular application to route dynamically like so: http://localhost:4200/mydomain/subdomain.

Now, how did I tackle this challenge? Started scratch my head!!! :(

Initially, I considered using APP Initializer, but it turned out to have some issues.

So, what’s the next step?

The data from the event listener is received in the app component and stored in the Ngrx store.
But how do I handle redirection based on this data? Enter the loading component with a ‘showLoading’ variable, and I started subscribing to the store.

myData$ = this.store.select(selectorName);
mySubscription = myData$.subscribe(data => {
  const { isLoaded, DomainA, SubDomainA } = data;
  if (isLoaded) {
    showLoading = false;
    if (SubDomainA !== '')
      this.router.navigateByUrl(`/${DomainA}/${SubDomainA}`);
    else
      this.router.navigateByUrl(`/${DomainA}`);
  }
});
Enter fullscreen mode Exit fullscreen mode

With this setup, navigation to the specific route is achieved. Now, the challenge is to use this dynamic value in the app routing.

In the app-routing.module.ts file:

export const Routes = [
  {
    path: ':dynamicPath',
    loadChildren: () =>
      import('./DomainA.module').then(mod => mod.DomainAModule),
    resolve: {
      dynamicPath: myResolver
    }
  },
];
Enter fullscreen mode Exit fullscreen mode

Next I created a myResolver.ts file to handle the resolution and return the data from the store:

resolve(): string {
  let myDatafromStore;
  let dynamicPath;
  myDatafromStore = this.store.select(SelectorName);
  const { isLoaded, DomainA, SubDomainA } = data;
  if (isLoaded) {
    if (SubDomainA !== '')
      dynamicPath = `/${DomainA}/${SubDomainA}`;
    else
      dynamicPath = `${DomainA}`;
  }
  return dynamicPath;
}
Enter fullscreen mode Exit fullscreen mode

In this way, Angular’s dynamic routing, coupled with the power of Ngrx store and resolver, allows for seamless handling of complex scenarios.
There are different ways to achieve this scenario but as per my requirement, this looks good and clean!
Happy Coding!

Top comments (0)