Can we dynamically change the lazy loaded module based on a specific flag? For instance, loading module A if the flag is active and module B otherwise. The crucial aspect is that both modules should use the same path
.
Approach #1 - dynamic loadChildren()
// Utilizing a service to access the flag value. This service would be injected in an appropriate location.
let someFlag = this.someService.getFlagValue();
const routes: Routes = [
{
path: 'routeA',
loadChildren: () => {
if (someFlag === true) {
return import('./A.module').then(m => m.ModuleA);
} else {
return import('./B.module').then(m => m.ModuleB);
}
}
}
];
However, encountering an error while trying to load the route:
Error: Uncaught (in promise): Error: Runtime compiler is not loaded
Approach #2 - Using canActivate guard instead of loadChildren
const routes: Routes = [
{
path: 'routeA',
canActivate: [CanActivateFeatureFlagGuard],
loadChildren: () => import('./A.module').then(m => m.ModuleA),
data: {
REPLACE_WITH: () => import('./B.module').then(m => m.ModuleB),
preload: false
}
}
]
This leads to a compile error:
Function expressions are not supported in decorators in 'routes'
'routes' contains the error at routing.module.ts
Pointing towards the line containing REPLACE_WITH.
Is there a known method (like using a CanActivate guard) to influence which module gets loaded?
Update: Discovered this repo that seemed promising, but implementation results in the error:
ERROR in Cannot read properties of undefined (reading 'loadChildren')