inorganik
inorganik

Reputation: 25535

Error: RouterModule.forRoot() called twice

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

Upvotes: 2

Views: 7828

Answers (2)

Konrad Gałęzowski
Konrad Gałęzowski

Reputation: 1993

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:

  1. Search for AppModule
  2. Find all import from all files except AppModule and main.ts
  3. Remove them and corresponding import statements.

Upvotes: 2

lealceldeiro
lealceldeiro

Reputation: 14978

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

Upvotes: 5

Related Questions