What’s an injection context?

In the past few months, the introduction of the inject() function and the takeUntilDestroyed operator shared something important: While these features are based on functions, these functions have to run within an Angular injection context, or you’ll get errors from the framework.

That’s because Angular relies on dependency injection for almost everything. As a result, it’s helpful to know what is an injection context.

The most apparent injection contexts are these:

  • Constructor of an “Angular class” such as services, components, directives, pipes, etc.
  • In the initializer for fields of such classes.

Here is an example of what is and isn’t an injection context:

Other places are injection contexts:

  • In the factory function specified for useFactory of a Provider or an @Injectable.
  • In the factory function specified for an InjectionToken.
  • Within a stack frame that is run in an injection context.

In other words, this is when you’re configuring a module or dependency injection. The most common examples are related to the router – guards, resolvers, and such are all in the injection context, so we can inject dependencies there: