[英]Trouble injecting service into another service (singleton), Angular2
I have two services, both are @Injectable. 我有两个服务,都是@Injectable。 ServiceA is provided to components via the Providers array and works great everywhere.
ServiceA通过Providers阵列提供给组件,并且可以在任何地方使用。 ServiceB is a singleton and is in the Providers array of its module and works great everywhere.
ServiceB是一个单例,位于其模块的Providers数组中,无处不在。 ServiceA needs to remain not a singleton, and ServiceB needs to remain a singleton.
ServiceA需要保持不是单身,而ServiceB需要保持单身。
My issue is that now I need to access ServiceA from ServiceB, but don't know how to access it. 我的问题是,现在我需要从ServiceB访问ServiceA,但不知道如何访问它。 Seems I cannot inject a non-singleton service into a singleton.
似乎我无法将非单身人士服务注入单身人士。
Everything I come across tells me to put the service in bootstrap or module declaration but as I mentioned I cannot do that as I need ServiceA to behave as a non-singleton. 我遇到的一切都告诉我将服务放在bootstrap或模块声明中,但正如我所提到的,我不能这样做,因为我需要ServiceA表现为非单例。
// module setup
... providers: [ServiceB]
// non-singleton
@Injectable()
export class ServiceA
// singleton
@Injectable()
export class ServiceB {
constructor(ServiceA) // <-- this is the problem area, need to get ServiceA here
I have tried doing something like constructor(Inject(ServiceA) serviceA) but seem to get the same errors with that 我尝试过像构造函数(Inject(ServiceA)serviceA)这样的东西,但似乎得到了相同的错误
Error: DI Error No provider for ServiceA!
错误:DI错误没有ServiceA的提供商!
You can declare ServiceA
both in @Component.providers
and @NgModule.providers
: 您可以在
@Component.providers
和@NgModule.providers
声明ServiceA
:
ServiceA
in a component's constructor, you'll get the component-scoped instance (corresponding to the @Component.providers
declaration). ServiceA
时,您将获得组件范围的实例(对应于@Component.providers
声明)。 ServiceA
in another service's constructor (in your case: when injecting ServiceA
in ServiceB
), you'll get the global instance (corresponding to the @NgModule.providers
declaration). ServiceA
在另一个服务的构造函数(你的情况:当注射ServiceA
在ServiceB
),你会得到全局实例(对应于@NgModule.providers
声明)。 In other words, if you redeclare a service in a component's providers ( @Component.providers
), it will "shadow" the instance that was declared globally in @NgModule.providers
. 换句话说,如果您在组件的提供程序(
@Component.providers
)中重新声明服务,它将“ @NgModule.providers
在@NgModule.providers
全局声明的实例。
WORDS OF CAUTION: 小心的话:
ServiceA
into ServiceB
AND ServiceC
, then B and C would get the same instance of A. ServiceA
注入ServiceB
和ServiceC
,那么B和C将获得相同的A实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.