1 year ago

#76573

test-img

Matej Šranc

Angular router - dynamic routes from graphQL

I am banging my head against the monitor for the last day and a half..

We are working on a headless website, front-end will be decoupled from back end. And we have some issues.

1.) I am trying to dynamically create routes in Angular 12. First I call graphQL which returns all routes currently available. Then I loop through those routes one by one and add them to the router using:

this.router.config.push({ path: 'url/from/QL/server', component: HomeComponent, pathMatch:'full' });

After that I call:

this.router.resetConfig(this.router.config);

If I try to list all of the routes, they show up on the list, but i still get:

Error: Cannot match any routes. URL Segment: 'url/from/QL/server'

If I pack the exact same code in setTimeout, then the paths work, no matter the time set in setTimeout. The only difference is that the routes are hardcoded and did not come from graphQL, but the list of routes is exactly the same. How is that possible?

2.) Also another thing. Is there a way to load angular app after the router is set? When I set routes in setTimetout manually (which works after setTimeout executes) and refresh a page on a sublink, then again I get the above error, because routes are not set yet (because setTimeout). I have tried to set the router with some routes and then set loaded=true; and used this variable in:

<router-outlet *ngIf="loaded"></router-outlet>

Is there maybe another way to prevent app from loading until routes are set (until I set loaded=true);

I hope this all makes sense and that I did not complicate things too much.

Any help will be greatly appreciated.

angular

graphql

angular-routing

angular-router

angular12

0 Answers

Your Answer

Accepted video resources