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?
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
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.
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