Search code examples
angularangular-routerangular-universal

Angular 5 set routes from API with Angular Universal


I'm using Angular Universal Starter for my application and I try to build a dynamic routing system from an API. I would like to configure my routing system before the application bootsrap. To do this, I used the APP_INITIALISER. I followed different way, especially this one : Angular 5 Build routes from API data at startup

My problem come on my app.module.ts file :

export function initRoutes(routes: RouterService) {
    return () => routes.browse();
}

@NgModule({
    imports: [
        BrowserModule.withServerTransition({appId: 'universal'}),
        BrowserAnimationsModule,
        RouterModule.forRoot([]),
        TransferHttpCacheModule,
        HttpClientModule,
        InjectorModule,
        HomeModule,
    ],
    declarations: [
        AppComponent,
    ],
    entryComponents: [
        HomeComponent
    ],
    providers: [
        NetworkService,
        RouterService,
        {
            'provide': APP_INITIALIZER,
            'useFactory': initRoutes,
            'deps': [ RouterService ],
            'multi': true,
        },
        Title,
        MenuService
    ],
    bootstrap: [AppComponent]
})

When I import TransferHttpCacheModule (an interceptor that avoids duplicate HttpClient requests on the client, for requests that were already made when the application was rendered on the server side), I'm getting the following error :

enter image description here

My question is : Is it possible to send a JSON (with a routes list) to configure my routing system on an SSR application ?


Solution

  • You can use an array like this:

    export const appRoutes: Routes = [
      {
        path: 'aRoute',
        component: NameComponent
      },
      ...
    ]
    

    and in the NgModule imports add this:

    RouterModule.forRoot(appRoutes),
    

    then if you go to the path aRoute, NameComponent will be rendered.