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
.
Providers are classes that create and manage service objects the first time that Angular needs to resolve a dependency. Providers is used to register the classes to an angular module as a service. And then, this service classes can be used by other components during the itself creation phase in the module.
There are four ways by which you can create the dependency: They are Class Provider (useClass), Value Provider (useValue ), Factory Provider ( useFactory ), and Aliased Class Provider ( useExisting).
The useExisting provider key lets you map one token to another. In effect, the first token is an alias for the service associated with the second token, creating two ways to access the same service object.
A dependency provider configures an injector with a DI token, which that injector uses to provide the concrete, runtime version of a dependency value. The injector relies on the provider configuration to create instances of the dependencies that it injects into components, directives, pipes, and other services.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With