Dynamically loadChildren in Angular based on service value condition

237 views Asked by At

Is possible to loadChildren routes in Angular based on a service based value condition?

I have the following route to be loaded:

const routesFactory = (service: InjectedService) => {
  return [
    {
      path: "",
      runGuardsAndResolvers: "always",
      canActivate: [ApplicationStateGuard],
      canActivateChild: [ApplicationStateGuard],
      loadChildren: (): Promise<LayoutModuleV1 | LayoutModuleV2> =>
        service.condition == true
          ? import(/* webpackChunkName: "layout-v1" */ "@app/layout-v1").then((mod) => mod.LayoutModuleV1)
          : import(/* webpackChunkName: "layout-v2" */ "@app/layout-v2").then((mod) => mod.LayoutModuleV2),
    },
  ]
}

// later in the AppRouting I use as follow:

@NgModule({
  exports: [RouterModule],
  imports: [RouterModule.forRoot(routes, { onSameUrlNavigation: "reload", relativeLinkResolution: "legacy" })],
})
export class AppRouting {
  static forRoot(): ModuleWithProviders<AppRouting> {
    return {
      ngModule: AppRouting,
      providers: [
        Service,
        {
          provide: ROUTES,
          useFactory: routesFactory,
          deps: [InjectedService],
          multi: true
        }
      ]
    }
  }
}

// AppModule

imports: [AppRouting.forRoot()]

The problem is that I have a circular dependency with the InjectedService.

Error: NG0200: Circular dependency in DI detected for Router. Find more at https://angular.io/errors/NG0200
    at throwCyclicDependencyError (core.js:228:11)
    at R3Injector.hydrate (core.js:11453:13)
    at R3Injector.get (core.js:11276:33)
    at injectInjectorOnly (core.js:4770:33)
    at Module.ɵɵinject (core.js:4774:12)
    at Object.InjectedService_Factory [as factory] (injected.service.ts:71:25)
    at R3Injector.hydrate (core.js:11457:35)
    at R3Injector.get (core.js:11276:33)
    at injectInjectorOnly (core.js:4770:33)
    at ɵɵinject (core.js:4774:12)

It is possible to provide the condition to be used inside the Routing provider without using the Services condition directly?

Could be possible to only set dynamic loadChildren inside the ROUTES multiprovider and the rest of the routes inside the RouterModule.forRoot(routes, …) ?

0

There are 0 answers