1

I am trying to conditionally load modules (built for varying layouts) based on data received from the API. The data is fetched based on a value of a pathparam. I have tried following route config below:

path: ':objectId',
loadChildren: async () => {
      const service = AppInjector.get(ObjectService);
      const activatedRoute = AppInjector.get(ActivatedRouteSnapshot);
      const obj = await ObjectService.get(activateRoute.paramsMap['objectId']);
      if (obj.type === 'one') {
        const a = await import('./modules/layouts/one.module');
        return a.OneModule;
      }
      const b = await import('./modules/layouts/two.module');
      return b.TwoModule;
    }
  }

This throws a Null Injector error for ActivatedRouteSnapshot.

I have also tried to use ActivatedRoute with subscribe but the pathparam is not filled in. It seems as though the parameter is filled in after loadChildren has been executed.

Any help on how can achieve above would be great.

Thanks!

  • You can use canLoad router guard. – GRD Mar 05 '22 at 15:37
  • I would be able to get the pathparam and run API call in the guard but how can I lazy load the module in a router guard? is there a way to pass variable from guard to loadChildren object? Also, the objectId is variable not deterministic at compile time. – Shubham Kansal Mar 05 '22 at 16:13
  • 1
    ActivatedRoute only work when into the component, because it's base on the tree route in Angular so in routing module you never get params from ActivatedRoute. There's a bad way that you can get params through url get by window – Huấn Nguyễn Xuân Mar 06 '22 at 07:14
  • so, window.location.pathname and then parse for objectId? Would angular route config take precedence? i.e. if there's another hardcoded route {path: "/home", component: HomeComponent}; then we wouldn't want the {path: "/:objectId"} to be run. In this case HomeComponent should be displayed. – Shubham Kansal Mar 06 '22 at 13:47

0 Answers0