I want to load different component with dependent resolver which has same path value in child routes
parent:
path: 'test',
loadChildren: () =>
import('./myRoutingModule').then(
(m) => m.myDynamicRoutes),
child:
export const myDynamicRoutes: Routes = buildMyRoutes();
export function buildRoutes(): Route[] {
var version = inject(myService);
if (version === 1) {
return [
{
path: '',
component: oneComponent,
resolve: {
initData: oneResolver,
},
},
];
} else if (version === 2) {
return [
{
path: '',
component: twoComponent,
resolve: {
initData: twoResolver,
},
},
];
}
I'm not allowed to use inject here is there a way i can use ? are there better alternatives to set routes dynamically. i'm on angular 17 standalone components
Routes are not dynamic to my knowledge. It's only run once, so you need to use the CanMatchFn
to handle this scenario, so as to conditionally allow access to the routes based on the flag:
export const myDynamicRoutes: Routes = [
{
path: '',
component: oneComponent,
canMatch: [CanMatchRoute],
resolve: {
initData: oneResolver,
},
data: { version: 1 },
},
{
path: '',
component: twoComponent,
canMatch: [CanMatchRoute],
resolve: {
initData: twoResolver,
},
data: { version: 1 },
},
The can activate can contain the inject and conditionally do the routing:
const canMatch: CanMatchFn = (route: Route, segments: UrlSegment[]) => {
var service = inject(myService);
return route?.data?.version === service?.version;
};