C
C
CoyoteSS2020-07-26 14:40:34
Angular
CoyoteSS, 2020-07-26 14:40:34

When should UseExistingProvider be used?

As for DI in Angular, I have the only question that torments me for a long time, I don’t understand the purpose of the useExisting provider and how it differs from useClass, and also where to apply it. I have a very vague idea about it, at the moment I have the following thoughts on useExisting:
!!! Everything below is false information and nonsense, but I want you to understand what my idea of ​​\u200b\u200bhe is.
1) useExisting does not create a new dependency instance, but creates a link to it under another class that serves as its replacement (alias).
2) useExisting should be used together with useClass, i.e. the class that is specified in { provide: SomeClass } must be both the token itself and the source of the dependency, and must be injected at a hierarchy level somewhere higher than useExisting, or at the same level, but ultimately it must still be injected as { provide: SomeClass, useClass: SomeClass }
3) The alias class that we inject must fully match the interface of the original class we are going to replace with.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Shvets, 2020-07-27
@Xuxicheta

1) useExisting does not create a new dependency instance, but creates a link to it under another class that serves as its replacement (alias).

not a link and not under another class.
When you provide an entity, you tell the di-container (we have an injector) a di-token, according to which the injector gives you entities.
The class for it is a special case of di-token.
It is possible to do so
providers: [{
  provide: 'doc',
  useExisting: DOCUMENT
}]

Read more here https://angular.io/guide/dependency-injection-prov...
2) useExisting should be used together with useClass

Again, not necessarily a class, the main thing is that the entity associated with the token in useExisting is already known to the injector.
3) the alias class that we are implementing must fully comply with the interface of the original class that we are going to replace with.

Not necessarily, the injector does not check your types, it just outputs what it remembers.
And on the main issue
When should UseExistingProvider be used?

When you need to provide an existing entity under a different token. Let's say some other classes inject dependencies for themselves using a well-known token, so that they can find our instance using it.
Angular is full of stuff like this, HttpClient injects HTTP_INTERCEPTORS, form directives inject NG_VALIDATORS, bootstrap injects APP_INITIALIZER, etc.
Together with the classes, useExisting is practically not used, I don’t see the point.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question