Explore Angulars inject function, possible use cases, and anti-patterns
Angular v14 contains many great features. Besides standalone components and typed forms, the
inject function was one of the most talked-about features on Twitter. But what is it all about? Let’s find out?
In a nutshell, the
inject function is a function that allows you to inject an Injectable. And well, it’s nothing new; in fact, it has already existed since Angular v9. But its use case was limited.
Inject function in Angular 9
We could use the
inject function either in a factory function when declaring a new
InjectionToken or inside the provider’s array of an
Injectable. Let’s take a look.
Okay, got it. So what changed with Angular 14?
Inject function in Angular 14
With Angular 14, the use of the
inject function is no longer limited to
factory functions. From now on, you can use the
inject function in your components, directives, and even pipes.
Cool, so what does that look like?
Imagine you have a
CustomersComponent that displays a list of customers. The customers are provided by a
CustomerService which is injected in the
Good old dependency injection via
constructor. Nothing special. So let’s go ahead and refactor this code to use the new
CustomerService without the usage of a
constructor. We use the
inject function to directly assign the injected…