[英]Error: RouterModule.forRoot() called twice
I have a component ListComponent
that needs to be used in 2 modules, one of them is lazy loaded.我有一个组件ListComponent
需要在 2 个模块中使用,其中一个是延迟加载的。 So I created SharedModule that declares ListComponent.所以我创建了声明 ListComponent 的 SharedModule。 ListComponent uses the routerLink
directive, so it needs RouterModule. ListComponent 使用了routerLink
指令,所以它需要 RouterModule。 So I imported RouterModule, which resulted in this error.所以我导入了RouterModule,导致了这个错误。
core.js:1598 ERROR Error: Uncaught (in promise): Error: RouterModule.forRoot() called twice. core.js:1598 错误错误:未捕获(承诺):错误:RouterModule.forRoot() 调用了两次。 Lazy loaded modules should use RouterModule.forChild() instead.延迟加载的模块应该使用 RouterModule.forChild() 代替。
A global search shows I am only calling RouterModule.forRoot
once.全局搜索显示我只调用RouterModule.forRoot
一次。 My lazy-loaded module calls RouterModule.forChild
and is the only other routing module.我的延迟加载模块调用RouterModule.forChild
并且是唯一的其他路由模块。
I created a stackblitz with my exact same setup, but wasn't able to recreate the issue.我使用完全相同的设置创建了一个 stackblitz,但无法重现该问题。 It actually works.它确实有效。 Still, I can't figure out what's different about my project.尽管如此,我还是不明白我的项目有什么不同。 https://stackblitz.com/edit/angular-shared-component-b 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:如果您只需要在SharedModule
中导入RouterModule
以使用诸如routerLink
之类的指令,您可以像这样简单地导入它:
// ...
@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.确保应用程序将基本模块(通常AppModule
,也许AppRoutingModule
你的情况),您导入RouterModule.forRoot(yourRoutes)
所以在使用的链接ListComponent
正常工作。
See more in RouterModule API Docs在RouterModule API 文档中查看更多信息
In my case the problem was AppModule
auto-imported by IDE in one of page.modules.ts
在我的情况,问题AppModule
通过IDE中的一个自动导入page.modules.ts
You can quickly check if that's an issue:您可以快速检查这是否有问题:
AppModule
搜索AppModule
AppModule
and main.ts
从除AppModule
和main.ts
之外的所有文件中查找所有导入
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.