I am running into 'opaque tokens' as a solution to implementing global constants in Angular 2, for example here: Define global constants in Angular 2
Despite reading the docs, I can't seem to grasp the point.
Using an OpaqueToken is preferable to using strings as tokens because of possible collisions caused by multiple providers using the same string as two different tokens.
What? What's an Angular2 token to begin with? All I get on google are answers on JSON Web Tokens (their role in auth, etc, etc), which I understand, but are obviously not related in any way.
What's an Opaque Token? What is it used for?
P.S. More docs on opaque tokens as used to provide constants. They didn't help me very much, however.
update Angular4
In Angular4
OpaqueTokenis deprecated and will be replaced byInjectionToken. InjectionToken allows to pass a generic type parameter.See also
original
A token is a key for providers of Angulars dependency injection. Providers are registered with a key and components, directives, and service classes instantiated by DI get dependencies injected which are looked up by provider keys.
DI supports types, strings,
OpaqueTokenand objects as keys.The object key (
APP_CONFIG_2) and theOpaqueToken(APP_CONFIG) need to be the exact same instance. A different instance with the same content won't work. This makes it easy to look up where the key is declared and whether the provider and the injection target use the same key.For a string it can be a different instance, this brings the risk, that the same string value is used in different modules and might cause conflicts or the wrong provider being injected.