如何在 2 个延迟加载的模块之间共享相同的服务实例——而不是在 root 中 [英] how to share same service instance between 2 lazy loaded modules - not at root

查看:16
本文介绍了如何在 2 个延迟加载的模块之间共享相同的服务实例——而不是在 root 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在两个延迟加载的模块之间共享相同的服务实例,而根注入器不提供该服务?或者至少,直到被要求才提供?

Is it possible to share the same instance for a service, between two lazy loaded modules, where that service is not provided at the root injector? Or at least, not provided until called upon?

例如我有 LazyModuleALazyModuleB,它们被命名为延迟加载.这些模块中的每一个都需要访问相同的服务,但其他任何地方都不需要该服务.共享服务应该只有一个在模块之间共享的实例.此外,不应在这两个模块之外加载或访问它.

E.g. I have LazyModuleA and LazyModuleB that are, as named, loaded lazily. Each of these modules need access to the same service, but that service is not needed anywhere else. The shared service should only have a single instance shared among the modules. Also, it should not be loaded or accessible outside those two modules.

目前我通过 {providedIn: 'root'} 在根注入器中提供服务.是否可以为这两个延迟加载模块加载此服务的相同实例?

Currently I'm providing the service in the root injector via {providedIn: 'root'} . Is it possible to load the same instance of this service for both of these lazy loaded modules?

推荐答案

有趣,我不确定这是否可行,我自己没有尝试过,如果您有第 3 个模块怎么样,里面有您的没有 providerIn: root 的服务.

Interesting, I am not sure if this would work, I haven't tried myself, how about if you have a 3rd module, in it, there is your service without providerIn: root.

您的服务:

@Injectable()
export class MySharedService {
 // ... some code
}

第三个模块:

@NgModule({
   providers: [MySharedService],
   exports: [MySharedService] // I'm not sure if this is need it 
})
export class ModuleC {}

懒惰模块A:

@NgModule({
   import: [ModuleC]
})
export class LazyModuleA {}

懒惰模块B:

@NgModule({
   import: [ModuleC]
})
export class LazyModuleB {}

所以你的 LazyModuleALazyModuleB 都导入了 ModuleC,它正在导出你想要的 service.

So your LazyModuleA and LazyModuleB both have imported ModuleC which is exporting your desired service.

这篇关于如何在 2 个延迟加载的模块之间共享相同的服务实例——而不是在 root 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆