如果我导入我的模块,我的服务就不是单例的,但如果我不导入,我的控制器就无法工作

If I import my module, my services aren't singleton, but if I don't, my controllers don't work

我的项目设置如下:

这不会引发任何错误,但在 sharedService 构造函数中设置断点表明它不是单例。


我可以改为将我的导入更改为:

sharedService 现在看起来是单例,但我得到一个错误

Component sharedComponentis not part of any NgModule or the module has not been imported into your module

我希望我的共享服务是单例的,但需要访问共享组件。我做错了什么?

对于遇到此问题的任何其他人,我对共享模块应包含的内容存在核心误解。 The docs say:

Create a SharedModule with the components, directives, and pipes that you use everywhere in your app. This module should consist entirely of declarations, most of them exported.

The SharedModule may re-export other widget modules, such as CommonModule, FormsModule, and modules with the UI controls that you use most widely.

The SharedModule should not have providers for reasons explained previously. Nor should any of its imported or re-exported modules have providers. If you deviate from this guideline, know what you're doing and why.

Import the SharedModule in your feature modules, both those loaded when the app starts and those you lazy load later.

Create a CoreModule with providers for the singleton services you load when the application starts.

Import CoreModule in the root AppModule only. Never import CoreModule in any other module.

Consider making CoreModule a pure services module with no declarations.

将我的共享服务从 SharedModule 移到 CoreModule 是解决方案。