Search code examples
javascripttypescriptangularangular2-services

Angular 2 useExisting providers


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.


Solution

  • 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