Search code examples
angulartypescriptangular-cliangular-compiler

Recursive routing causes maximum stack exceeded error


I've got a PageModule which reference itself in it's routing. It works if I remove the circular dependency, start the app and then add it again. But not if I stop the server and start it again with the circular dependency already there. How can I solve this?

I have this router module:

const routes: Routes = [
  {
    path: '',
    component: PageComponent,
    children: [
      {
        path: ':pageId',
        loadChildren: 'app/routes/+dashboard/routes/+pages/routes/+page/page.module#PageModule'
      }
    ]
  }
];

@NgModule({
  imports: [RouterModule.forChild(routes)]
})

export class PageRouterModule {}

Which is then imported into PageModule:

@NgModule({
  imports: [
    PageRouterModule
  ],
  exports: [PageRouterModule],
  declarations: [PageComponent]
})

export class PageModule {}

Apparently this was supposedly fixed as seen here, but I've upgraded to the latest cli version which is 1.5.0 but the issue is still there.


Solution

  • I found that changing this line:

    loadChildren: 'app/routes/+dashboard/routes/+pages/routes/+page/page.module#PageModule'
    

    To:

    loadChildren: loadModule
    

    Where loadModule is an exported function:

    export function loadModule() {
      return PageModule;
    }
    

    In theory you can do () => PageModule too but that will cause a lambda error so you must use the exported function as shown above.

    I hope this helps someone else.