Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

useClass vs useExisting

Tags:

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:

  • Angular 2 useExisting providers
  • useValue vs useFactory
  • Angular 2 useExisting providers

but would like to have more real examples

like image 219
Stepan Suvorov Avatar asked Jul 17 '17 20:07

Stepan Suvorov


People also ask

What is useClass in Angular?

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.

What is useExisting in Angular?

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.

When should I use useFactory method?

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.

What is provide and useValue in Angular?

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.


2 Answers

useExisting - create refrence to service example here
useClass - create new instance of service example here

like image 113
izik f Avatar answered Sep 29 '22 09:09

izik f


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.

like image 35
Günter Zöchbauer Avatar answered Sep 29 '22 10:09

Günter Zöchbauer