Christian Vincenzo Traina
Christian Vincenzo Traina

Reputation: 10444

In which cases using "provide" and "useClass" can be useful?

According to Angular Docs, you can inject a different object when a provider is a required. When I looked for good reasons to do this, the only information that I found has been the following:

Suppose an old component depends upon an OldLogger class [...] but for some reason you can't update the old component to use it.

I'm still doubtful. Why, in some cases, I couldn't update the old component? It's not dangerous if a Component or a Directive expects a class and we inject another one? What are the cases where using provide and useClass is essential?

Upvotes: 6

Views: 3671

Answers (3)

Dm Mh
Dm Mh

Reputation: 840

useClass can be used to (kind of) fulfil dependency inversion design principle (aka DIP). But as far as I understand, DIP is not fulfilled since a module depends on a concrete implementation specified under useClass

Upvotes: 0

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657741

useClass is for providing alternative implementations

{ provide: MyClass, useClass: MyMockClass }

which means that when MyClass is the type of the constructor parameter where an instance should be injected, a MyMockClass instance is injected instead.

useValue is to make Angular use a custom instance creation logic

providers: [
  DebA, 
  DebB,
  { provide: MyClass, useValue: (a, b) => new MyClass(a, b), deps: [DepA, DebB] }
]

or

{ provide: 'myServerPort', useValue: 8080 }

where Angular wouldn't have a way to provide a value for 'myServerPort' if not useValue would be available.

Upvotes: 5

Abhishek Singh
Abhishek Singh

Reputation: 910

In my case I use it when I need to implement different logic other than a default class provided by the angular. For example ErrorHandler is a default class for handling errors in Angular 2+ but I like to use my custom classes for handling errors So I use

{ provide: ErrorHandler, useClass: MyErrorHandler }

It will tell the angular to use MyErrorHandler class instead of ErrorHandler

Upvotes: 6

Related Questions