Created by Chau Tran
createInjectionToken is an abstraction over the creation of an
InjectionToken and returns a tuple of
[injectFn, provideFn, TOKEN]
InjectionToken is usually not a big deal but consuming the
InjectionToken might be a bit of a chore/boilerplate if the project utilizes
InjectionToken a lot.
createInjectionToken accepts a second argument of type
CreateInjectionTokenOptions which allows us to customize the
InjectionToken that we are creating:
createInjectionToken creates a
providedIn: 'root' token so we do not have to provide it anywhere to use it. To create a non-root token, pass in
More than often,
InjectionToken can depend on other
InjectionToken. This is where
deps come in and what we can pass in
deps depends on the signature of the
We can also pass in other providers, via
createInjectionToken so when we call
provideFn(), we provide those providers as well.
As the name suggested, we can also create a multi
createInjectionToken by passing
multi: true to the
If we already have an
InjectionToken that we want to turn into
provideFn, we can pass that token, via
One use-case is if our factory has a dependency on the same
InjectionToken (i.e: a hierarchical tree-like structure where child
Service might optionally have a parent
Note that if
token is passed in and
createInjectionToken will throw an error.
As the name suggested,
createNoopInjectionToken is the same as
createInjectionToken but instead of factory function, it accepts description and options. This is useful when we want to create a
multi token but we do not have a factory function.
It also supports a generic type for the
InjectionToken that it creates:
Even though it’s meant for
multi token, it can be used for non-multi token as well:
createNoopInjectionToken returns a
provideFn which is a function that accepts either a value or a factory function that returns the value.
In the case where the value of the token is a
NG_VALIDATORS is a multi token whose values are functions),
provideFn accepts a 2nd argument to distinguish between a factory function or a function as value
provideFn will treat the function as a factory function. If we want to provide the function as-is, we need to pass in
true as the second argument.
injectFn returned by
createInjectionToken also accepts a custom
Injector to allow the consumers to call the
outside of an Injection Context.
Sometimes, it is required for root tokens to be initialized in
ENVIRONMENT_INITIALIZER. Instead of providing
ENVIRONMENT_INITIALIZER manually, we can retrieve the initializer provider function from
createInjectionToken to do so.