【问题标题】:If I import my module, my services aren't singleton, but if I don't, my controllers don't work如果我导入我的模块,我的服务不是单例的,但如果我不导入,我的控制器将无法工作
【发布时间】:2017-10-12 00:09:46
【问题描述】:

我的项目设置如下:

  • 应用程序
    • app.module (imports: [])
    • 共享
      • shared.module (declarations: [sharedComponent], providers: [sharedService])
      • 共享服务
      • 共享组件
    • 模块1
      • module1.module (imports: [sharedModule])
      • module1.component(路由子使用sharedComponent)
    • 模块2
      • module2.module (imports: [sharedModule])
      • module2.component(路由子使用sharedComponent)

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


我可以将我的导入改为:

  • 应用程序
    • app.module (imports: [sharedModule])
    • 共享
      • shared.module (declarations: [sharedComponent], providers: [sharedService])
      • 共享服务
      • 共享组件
    • 模块1
      • module1.module (imports: [])
      • module1.component(路由子使用sharedComponent)
    • 模块2
      • module2.module (imports: [])
      • module2.component(路由子使用sharedComponent)

sharedService 现在似乎是单例,但我收到错误消息

组件 sharedComponent 不是任何 NgModule 的一部分,或者该模块尚未导入您的模块中

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

【问题讨论】:

  • 我认为您需要将shared 设为provider 而不是module
  • 你能告诉我们你的sharedModule吗?

标签: angular angular2-routing angular2-services


【解决方案1】:

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

使用组件、指令和管道创建一个SharedModule 您在应用程序的任何地方都可以使用。该模块应完全由 声明,其中大部分是导出的。

SharedModule 可以重新导出其他小部件模块,例如 CommonModule、FormsModule 和带有 UI 控件的模块 使用最广泛。

SharedModule 不应有提供者,原因已解释 之前。它的任何导入或重新导出的模块也不应该有 提供者。如果您偏离本指南,请知道您在做什么 以及为什么。

在您的功能模块中导入 SharedModule,这两个模块都已加载 当应用程序启动以及您稍后延迟加载的应用程序时。

创建一个 CoreModule,其中包含您加载的 单例服务的提供者 当应用程序启动时。

仅在根 AppModule 中导入 CoreModule。从不导入 CoreModule 在任何其他模块中。

考虑让 CoreModule 成为一个纯服务模块,没有 声明。

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

【讨论】:

    猜你喜欢
    • 2021-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-18
    • 2022-01-22
    • 2017-05-21
    • 1970-01-01
    • 2017-05-16
    相关资源
    最近更新 更多