问题描述
useExisting
提供程序的用途是什么?
What are the usages for useExisting
provider?
是useExistingOrThrowIfThereIsNone
还是useExistingOrCreateIfThereIsNone
?是否可以根据我们的需要有目的地选择其中一种行为?如果其中一个不受支持,是否可以模拟不受支持的一个?
Is it useExistingOrThrowIfThereIsNone
or useExistingOrCreateIfThereIsNone
? Can one of these behaviours be chosen on purpose somehow, depending on our needs? If one of them is not supported, can an unsupported one be emulated?
文档对此完全不清楚,仅举例说明 useExisting
可以重用 useClass
中的实例.
The documentation is totally unclear on that and just gives an example that useExisting
can reuse an instance from useClass
.
推荐答案
以这个例子
providers: [
A,
{provide: B, useClass: A},
{provide: C, useExisting: A}]
如果你有
constructor(private a: A)
为第一个提供者创建了一个实例.
an instance for the first provider is created.
constructor(private b: B)
为第二个提供者创建了一个实例
an instance for the 2nd provider is created
constructor(private c: C)
注入第一个提供者的实例.
the instance of the first provider is injected.
如果你重新开始
constructor(private c: C)
创建并注入第一个提供程序的实例
an instance for the first provider is created and injected
这篇关于Angular 2 使用现有的提供者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!