将非单例服务注入 Angular 中的非单例服务

Dav*_*vid 13 dependency-injection angular

如果我想将非单例服务注入 Angular 中的另一个非单例服务,该怎么办?

假设我有一个ComponentA使用ServiceA这样的

@component({
  selector: "componentA",
  providers: [ServiceA]
})
export class ComponentA {
  constructor(private serviceA: ServiceA) {}
}
Run Code Online (Sandbox Code Playgroud)

现在,ServiceA也取决于ServiceB,所以我需要注入它

@Injectable()
export class ServiceA {
   constructor(private serviceB: ServiceB) {}
}
Run Code Online (Sandbox Code Playgroud)

我将如何/在哪里声明我的ServiceB? 在模块中?在那种情况下,那会是一个单身人士吗?

如果我将它添加到提供程序中,ComponentA它可以正常工作,但是我需要知道ComponentAServiceA取决于ServiceB,这对我来说似乎不太好。

谢谢!

fun*_*zer -1

服务在其提供的范围内始终是单例,因此如果您在模块中提供 B,那么对于使用该模块的每个人来说,它将是相同的单例。我认为您需要直接在服务 A 中使用 Injector 来按照您的方式进行操作。

请参阅https://angular.io/api/core/Injectable