Impossible to use dynamic routes with Angular Universal?!
See original GitHub issueProposal
What is the summary of the proposal?
It should be possible to use dynamically generated routes with Angular Universal.
What is the proposal?
In the docs it clearly states that it is necessary for Angular Universal to work to use initialNavigation=enabled
on the router. This, as the name already states, leads to (if I understand correctly) Angular performing the first navigation before i.e. the APP_INITIALIZER
s are loaded (which seems strange to me in the first place).
Now I assume that a common use case for using Angular Universal is to add server side rendering to pages powered by some sort of headless CMS. That is also what I am trying to achieve. Without initialNavigation=enabled
I had no problem to create the routes dynamically, after fetching page information from our backend. I basically execute this code within an APP_INITIALIZER
in my app.modules.ts
:
this.backendService.getStaticLinks().pipe(
tap(routes => {
const config = this.router.config;
config.unshift(
...routes.map(route => ({
path: route.path,
component: StaticContentComponent,
data: {
id: route._id
}
}))
);
this.router.resetConfig(config);
})
)
Now with initialNavigation=enabled
I always receive a 404 because I have no way of adding the routes, before the app tries to navigate there. The app still works with Universal support if I do not use initialNavigation=enabled
, but I get bad flickering, which is not acceptable to deliver it like this to the user.
Is there any way this problem can be solved?
edit: I am not entirely sure if this belongs to the Universal or the Angular Core team, so please feel free to move the ticket accordingly or let me know if I should open it somewhere else.
Issue Analytics
- State:
- Created 3 years ago
- Reactions:3
- Comments:12
After a lot of reading and trial-and-error I now found a solution to this issue. I feel that it is a little bit hacky, so I would really love some feedback on it. Also I still believe that this should be possible with Angular Universal, without hacking into
server.ts
andmain.ts
.Basically what I do now, is to fetch the data about the pages, both in the server and the app, before the Angular app gets bootstrapped at all. It look more or less like this:
server.ts
:and basically the same in
main.ts
:And then in my
app-routing.module.ts
I add the data provided inDYNAMIC_ROUTES
to the routes:So this does actually work. I am a bit unhappy about having to make the call twice (but couldn’t get it working otherwise). Also I would have preferred to avoid hacking into
server.ts
andmain.ts
.Any ideas on how to improve this? Or do you see any issues to take this into production?
This issue has been automatically locked due to inactivity. Please file a new issue if you are encountering a similar or related problem.
Read more about our automatic conversation locking policy.
This action has been performed automatically by a bot.