0

I went through answer from this question Angular 5 Build routes from API data at startup as a guide to load routes from backend, then I noticed that I can't navigate to those routes, that I loaded to routerConfig from API.

I found the reason for that and it turned out that my application is using server site rendering so I have initialNavigation set as 'enabled' and thats the reason that my routes not being registered. Docs says: "This value is required for server-side rendering to work."

I need solution to load routes from API while keeping SSR since app needs to be SEO friendly, is there is a good solution to do that ? as I am googling for a while and can't find anything usefull in those circumstances.

1 Answer 1

1

This is an example service to load your external routes.

@Injectable({
  providedIn: 'root'
})
export class RouteConfigService {

  constructor(
    private categoryService: CategoryService,
    private router: Router
  ) {
  }

  public loadRoutes(): Promise<any> {
    var promise = this.categoryService.list().then(t => {

      const config = this.router.config;
      config.push({ path: '', component: HomeComponent, pathMatch: 'full' });

      t.forEach(category => {
          config.push({ path: category.url, component: CategoryComponent });
      });

      this.router.resetConfig(config);

    });
    return Promise.resolve(promise);
  }
}

And then your app-routing.module.ts should look something like this:

@NgModule({
  imports: [RouterModule.forRoot([])],
  exports: [RouterModule],
  providers: [
    {
      provide: APP_INITIALIZER,
      useFactory: (routeConfigService: RouteConfigService) => 
        () => routeConfigService.loadRoutes(),
      deps: [RouteConfigService],
      multi: true
    }
  ],
})
export class AppRoutingModule { }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.