Angular 2 useExisting providers

Estus Flask picture Estus Flask · Jul 17, 2016 · Viewed 10k times · Source

What are the usages for useExisting provider?

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?

The documentation is totally unclear on that and just gives an example that useExisting can reuse an instance from useClass.

Answer

Günter Zöchbauer picture Günter Zöchbauer · Jul 17, 2016

With this example

providers: [
    A, 
    {provide: B, useClass: A}, 
    {provide: C, useExisting: A}]

If you have

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.

If you start fresh with

constructor(private c: C)

an instance for the first provider is created and injected