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
Angular creates factory for providers that will be used to instantiate provider.
I usually use the following table to understand the difference between types of providers.
As we can see in the picture above all of providers can be presented similar
useFactory
. When it's the time to get an instance of provider angular just callsfactory
function.So for
useClass
angular resolves dependency from parameters array and then calls constructor with parameters while foruseExisting
angular gets existing resolved instance and returns it.Use cases:
1) Don't expose full functionallity
2) Build tree
3) Avoid circular dependency
4) Provide common tokens
If we replace
useExisting
withuseClass
, then we’d be registering a new class instance