跨 AppModule 和库的单例服务

发布于 2025-01-18 06:59:34 字数 437 浏览 6 评论 0原文

上下文

我有一个包含两个库的角应用:dashboardlib和Chartslib。在我的应用程序的一个组件上,我有一个来自Dashboardlib的仪表板,仪表板本身使用Chartslib的图表。 我需要定义一个全局计时器来同步我的图表。因此,我在ChartsLib处理我的主题的setInterval中创建了一个服务TimerService,以同步图表。

图表正在收听计时器服务,而root应用程序正在启动计时器。

我尝试使用提供的服务

来注入我的服务:'root'(甚至提供:'platform')和forroot(),但是我仍然根应用程序和库本身之间无法拥有共享服务。

我认为我不了解工作方式如何共享服务,但是我不知道如何解决我的问题。

感谢您的回复。

Context

I have an angular app containing two libraries: DashboardLib and ChartsLib. On a component of my app I have a dashboard from DashboardLib and the dashboard itself use charts from ChartsLib.
I need to define a global timer to synchronize my charts. So, I created a service TimerService in ChartsLib handling setInterval of my Subject to synchronize the charts.

The charts are listening to the timer service and the root app is starting the timer.

Problem

I tried to Inject my service using providedIn: 'root' (even providedIn: 'platform') and forRoot(), but I still can't have a shared service between the root app and the library itself.

I assume I did not understand how work shared services, however I don't know how to solve my problem.

Thank you for your responses.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

魔法唧唧 2025-01-25 06:59:34

providedIn: 'root' 是正确的,但是您还需要在库中包含 @NgModule 声明(如果您尚未将服务包含为提供者)。然后,根应用程序需要在其导入中包含该模块。

@NgModule({
  declarations: [
   ...
  ],
  imports: [
    ...
  ],
  providers: [
    TimerService
  ],
  exports: [
    ...
  ]
})  
export class LibModule {}

根应用程序

@NgModule({
  declarations: [
    ...
  ],
  imports: [
    LibModule 
  ], 
})
export class AppModule { }

TimerService 还应该作为导出包含在库中的 public-api.ts 文件中(如果尚未包含)。

providedIn: 'root' is correct however you also need include an @NgModule declaration in your library if you aren't already and include the service as a provider. The root app then needs to include the module in its imports.

Library

@NgModule({
  declarations: [
   ...
  ],
  imports: [
    ...
  ],
  providers: [
    TimerService
  ],
  exports: [
    ...
  ]
})  
export class LibModule {}

Root App

@NgModule({
  declarations: [
    ...
  ],
  imports: [
    LibModule 
  ], 
})
export class AppModule { }

The TimerService should also be included as an export in your public-api.ts file in the library if it isn't already.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文