When should we use useExisting
provider instead of useClass
?
providers: [ {provide: Class1, useClass: Class1}, {provide: Class2, useExisting: Class2}]
REMARK: I have not found an exact question on SO. And for better indexing decided to create this specific one here, although I found this answers:
but would like to have more real examples
Use the Class Provider useClass , when you want to provide an instance of the provided class. The useClass expects us to provide a type. The Injector creates a new instance from the type and injects it. It is similar to calling the new operator and returning instance.
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.
To summarize, choose useValue to provide the same injected value each time*, useFactory when the injection value should be computed at runtime, and useClass when you want the injector to construct a value of Type<any> to provide.
useValue is a value provider that returns a fixed value for dependency injection. Injector does not create the object in this case, but we create the object and that object is configured with the provider using useValue. It is used in the following way.
useExisting - create refrence to service example here
useClass - create new instance of service example here
Normally you get an instance per provider.
{provide: Class1, useClass: Class1},
is equivalent with just
Class1
With
{provide: Class1, useClass: Class3},
you can configure, that when a constructor requests Class1
Angular DI creates an instance of Class3
and passes it to the constructor.
{provide: Class2, useExisting: Class2}
doesn't result in an instance being created, but you can see this rather than an alias. If a constructor requests Class2
, Angular DI looks for another provider for key Class2
and injects the instance from this Class2
provider. You can see useExisting
like a reference to another provider or an alias.
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