As you have probably already read, Angular 14 shipped some very interesting features: typed forms (which can still be improved, see how here), standalone components, and, the focus of this article, the ability to use the inject( ) function during the so-called constructor phase.
Let’s break the above sentence in 2.
What is the inject() function
The inject() function takes an InjectionToken as a parameter and returns the value for that InjectionToken from the currently active injector. Basically, it’s another way to get a hold of a dependency other than using constructor injection. Here’s an example.
Might seem like “it’s different, but the same”, but bear with me. You will see how powerfull this new mechanism really is.
What is the constructor phase
The constructor phase means the constructor function scope and field initializers. This means that you cannot call the inject() function inside @Input() setters or any other function or lifecycle hook. Here is an example to better understand it.
Good, now that we understood the basics let’s see what the fuss is about with a few simple examples.
Note that you can use the inject() function in Pipes and Directives aswell, double awesme!
Reducing component complexity with inject()
Imagine that you need a router path param in your component in order to fetch an entity details from the API.
Let’s see how that looked without using inject() function (or any other facade service for that matter).
The above example is the classic way of doing things, you would probably use a facade service to do the API calls, but other than that this should feel pretty familiar.