The inject() function

Next in our dependency injection series is the inject() function. You’re probably familiar with injecting services using class constructors as follows:

We can also use the inject function to do the same:

The inject function can be used in 3 different places. We can use it when initializing the field of an “Angular” class (component/service/pipe/directive/module) or in the body of the constructor of such a class:

Or it can be used in a provider factory function (see yesterday’s post as an example):

For now, we can consider that function as a syntax alternative. That said, we must start using it as soon as possible because router class guards have been deprecated in Angular 15.2. And the alternative is functional guards that might need dependencies injected – using the inject function:

Alain Chautard

Alain is a Google Developer Expert in Web Technologies, Angular, and Google Maps. His daily mission is to help development teams adopt Angular and build at scale with the framework. He has taught Angular on all six continents! A world traveler and photographer, Alain is also an international conference speaker, and a published author of several video courses.