Reputation: 6137
I have a module that has some routes:
export const routes: Routes = [
{
path: '/some-util-path',
component: SomeUtilComponent
}
];
@NgModule({
imports: [
CommonModule,
FormsModule,
RouterModule.forRoot(routes)
],
declarations: [
// --- some components ---
],
providers: [
// --- some services ---
],
exports: [
// --- some exports ---
],
})
export class MyUtilModule {
}
When I import this module in the app.module (root module) this works fine, but when I import it (as well) in a lazy-loaded module I get
Error: RouterModule.forRoot() called twice.
Lazy loaded modules should use RouterModule.forChild() instead.
How can I configure this Util Module to have the routes loaded as forRoot and forChild depending on its use-case?
I think I might split out the routes and 'SomeUtilComponent' to another Module that I only load in the app.module, but I'm interested in knowing if it is possible just with one module and conditional logic.
I was reading about the static forRoot and forChild methods, but I do not know how to arrange imports, as you can only specify providers.
Upvotes: 0
Views: 757
Reputation: 2782
Hi I think you need the export const routing: ModuleWithProviders = RouterModule.forChild(routes);
to make routing work here is a sample:
const routes: Routes = [{ path: '', component: LazyComponent }];
export const routing: ModuleWithProviders = RouterModule.forChild(routes);
and then in your lazy loading module do the next:
@NgModule({
imports: [routing],
declarations: [LazyComponent]
})
export class LazyModule {}
here is an article: Lazy Loading a Module
From Angular IO concerning lazy loading:
You might have noticed that the CLI adds RouterModule.forRoot(routes) to the app-routing.module.ts imports array. This lets Angular know that this module, AppRoutingModule, is a routing module and forRoot() specifies that this is the root routing module. It configures all the routes you pass to it, gives you access to the router directives, and registers the RouterService. Use forRoot() in the AppRoutingModule—that is, one time in the app at the root level. The CLI also adds RouterModule.forChild(routes) to feature routing modules. This way, Angular knows that the route list is only responsible for providing additional routes and is intended for feature modules. You can use forChild() in multiple modules.
Upvotes: 0