I have a component ListComponent
that needs to be used in 2 modules, one of them is lazy loaded. So I created SharedModule that declares ListComponent. ListComponent uses the routerLink
directive, so it needs RouterModule. So I imported RouterModule, which resulted in this error.
core.js:1598 ERROR Error: Uncaught (in promise): Error: RouterModule.forRoot() called twice. Lazy loaded modules should use RouterModule.forChild() instead.
A global search shows I am only calling RouterModule.forRoot
once. My lazy-loaded module calls RouterModule.forChild
and is the only other routing module.
I created a stackblitz with my exact same setup, but wasn't able to recreate the issue. It actually works. Still, I can't figure out what's different about my project. https://stackblitz.com/edit/angular-shared-component-b
If you only need to import the RouterModule
in SharedModule
in order to use directives such as routerLink
you can simply import it like this:
// ...
@NgModule({
imports: [RouterModule], // <-- without the .forRoot call
})
export class SharedModule { }
// ...
Make sure in the base module of you app (usually AppModule
, or maybe AppRoutingModule
in your case) you import it with RouterModule.forRoot(yourRoutes)
so the link used in ListComponent
work properly.
See more in RouterModule API Docs
In my case the problem was AppModule
auto-imported by IDE in one of page.modules.ts
You can quickly check if that's an issue:
AppModule
AppModule
and main.ts
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.