Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 554
Cristian Traìna Avatar asked Jan 29 '23 04:01

Cristian Traìna


2 Answers

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

like image 132
Abhishek Singh Avatar answered Jan 31 '23 18:01

Abhishek Singh


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.

like image 23
Günter Zöchbauer Avatar answered Jan 31 '23 18:01

Günter Zöchbauer