I can't figure out how to make this work without using shady magic wizards incentations so, I might be missing something.
My case example:
I have a Angular 18 SSR simple app with route home and user/:username
I dont want to query my database from my website so I need to get all my users beforhand and generate routes accordingly
If I receive this users data:
{ name: 'alice', email: '[email protected]' },
{ name: 'bob', email: '[email protected]' },
{ name: 'charlie', email: '[email protected]' },
I want to have Angular SSR to generate my website with routes:
I tried adding them dynamically like this
addUserRoutes(users: any[]) {
const newRoutes = users.map(user => ({
path: 'user/' + user.name,
component: UserComponent,
resolve: { user: user },
}));
this.router.resetConfig([...this.router.config, ...newRoutes]);
}
If I print my router.config I got all the routes I wanted but ofc SSR didnt generated them so I can't find them on my website which is why this solution is not working
I tried getting the data before bootstrap
export function initializeApp(http: HttpClient) {
return (): Promise<any> =>
firstValueFrom(
http
.get('generated/db-data.json')
.pipe(
map((data: any) => data.users),
));
}
export const appConfig: ApplicationConfig = {
providers: [
provideZoneChangeDetection({ eventCoalescing: true }),
provideRouter(routes),
provideClientHydration(),
provideAngularSvgIcon(),
provideHttpClient(),
{
provide: APP_INITIALIZER,
useFactory: initializeApp,
multi: true,
deps: [HttpClient],
},
]
};
But then I dont know how to use those users to update my routes array in my provideRouter(routes).
I am going to try to just use the data from initializeApp directly to create my routes array dynamically and try to use it directly updated in provideRouter(routes).
EDIT: I discusses with my coworkers and as it is, my database is actually a big json that I will stop doing async calls and deal with dependency injections etc and just
import userData from '../../public/generated/db-data.json';
function generateRoutes(): Routes {
const userRoutes = userData.users.map(user => ({
path: 'user/' + user.name,
component: UserComponent,
data: { user },
}));
return [
...userRoutes,
];
The best solution is to use Prerendering parameterized routes
where you specify which routes you want to prerender, then SSR, renders these routes as static routes, and there won't be unnecessary API calls to fetch the users in frontend.
You first need to configure a parameterized route like user/:username
or something like that.
Then you can write a script that generates the routes.txt
from an API call which gets the list of users from DB, then when you build the application, the routes.txt is processed and you will get the desired result.
This script will be processed by the angular application before running npm run start
or npm run build
...
"start": "node dynamic-routes.js && ng serve",
"build": "node dynamic-routes.js && ng build",
...