Tutorial hero
Lesson icon

The inject method

Originally published September 15, 2022 Time 2 mins

One of the interesting new features introduced in Angular 14 was the ability to use the inject function to inject dependencies as an alternative to dependency injection through the constructor.

This does not remove the ability the inject dependencies through the constructor, but its introduction was met with some differing opinions as to whether it’s a good idea or what patterns might be useful with the inject method.

Mostly, I think the dust is still settling on this one. I’ve seen a few different examples of interesting approaches, but I wanted to share this one from Manfred Steyer with you.

In Angular, we can create a guard to determine whether or not a particular route can be activated. Typically, this is done by creating a class that implements the CanActivate interface like this:

creating a class that implements the CanActivate interface

and then we would supply it to our route:

suppling it to our route

We implement the canActivate method that determines whether or not the route can be activated.

Often, this whole song and dance is done just to make a call to some AuthService to check if a user is authenticated or something like that.

However, the approach that Manfred demonstrated (which is available since Angular 14.2) looks like this:

functional guard instead of creating a class

The code above uses a functional guard instead of creating a class. Since we have access to the inject method we can easily inject the service we need to make our check.

Learn to build modern Angular apps with my course