The Hidden Power of InjectionToken Factory Functions in Angular

Netanel Basal
Netanel Basal
Published in
2 min readDec 7, 2020

In this article, I want to talk about a feature which Angular provides, that isn’t particularly well known or used by many developers. When using Angular InjectionToken, we can specify a factory function which returns a default value of the parameterized type T. For example:

This sets up the InjectionToken using this factory as a provider, as if it was defined explicitly in the application’s root injector. Now we can use it anywhere in our application:

But that’s not all. We can use the inject function to obtain a reference to other providers inside our factory function. Let’s see another real-world example:

In the above example, we inject the ActivatedRoute provider and return an observable for the timespan query param. Now we can use it in our components:

We can also pass InjectionFlags to the inject function. For example, we can say that the requested provider is optional:

Here’s another real-world example — let’s say you have a theme service, which exposes the current user’s theme:

The only data that most components need is the current theme. So instead of doing the following in each component:

We can create a provider with the sole purpose of providing the current user’s theme:

In summary, the benefits of using the InjectionToken factory function are:

  • The provider is tree-shakeable, since we don’t need to inject it in our app module as we’d do with the useFactory provider.
  • Using inject() to request a provider is faster and more type-safe than providing an additional array of dependencies (which is the common usage of useFactory providers).
  • The provider has a single responsibility, and our components are injected only with the data they need.
  • It makes testing more straightforward because we don’t need to mock everything. We can return a mock value from the factory, and that’s all.

🚀 In Case You Missed It

Here are a few of my open source projects:

  • Akita: State Management Tailored-Made for JS Applications
  • Spectator: A Powerful Tool to Simplify Your Angular Tests
  • Transloco: The Internationalization library Angular
  • error-tailer — Seamless form errors for Angular applications
  • Forms Manager: The Foundation for Proper Form Management in Angular
  • Cashew: A flexible and straightforward library that caches HTTP requests
  • Error Tailor — Seamless form errors for Angular applications

And many more!

Follow me on Medium or Twitter to read more about Angular, Akita and JS!

--

--

Netanel Basal
Netanel Basal

Written by Netanel Basal

A FrontEnd Tech Lead, blogger, and open source maintainer. The founder of ngneat, husband and father.

Responses (11)