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: