tl;dr: How does Angular know that an injection token passed to injector.get
corresponds with an injection token of a particular provider?
According to the Angular documentation, an InjectionToken
can be used to inject interfaces.
The example given is the following:
const myInterface = injector.get(new InjectionToken<MyInterface>('SomeToken'));
This would give me an instance that has been provided somewhere else.
In particular, somewhere, some piece of code has to provide an implementation of MyInterface
using a corresponding injection token.
My question is: How does Angular determine that the above injection token passed to injector.get
corresponds with whatever is supplied in the provider?
It appears to be a part of new InjectionToken<MyInterface>('SomeToken')
, so let's look at the options:
MyInterface
is out, because interfaces are erased during TypeScript compilation. The InjectionToken
docs say so themselves:
Use an
InjectionToken
whenever the type you are injecting is not reified (does not have a runtime representation) such as when injecting an interface (...)
It's not the 'SomeToken'
string, either, because, as the docs state:
Description for the token, used only for debugging purposes, it should but does not need to be unique
This leaves us with the InjectionToken
instance. So, does Angular check whether the InjectionToken
instance passed to injector.get
is the same as the one in the provider? It does not seem so, because in the above example, the instance is newly created - the provider cannot possibly have a reference to the same instance.
So, how does Angular know which provider to use for a given injection token?