Guards and resolvers can now be plain functions in Angular v14.2.0. The inject() function can be used inside the function if we also want to use DI. For example:

You can read this article to find out how it works.

Now that we can use plain JS functions, we can take advantage of the power of functions in JS. In other words, we can compose or create higher-order functions. Most applications usually have a route guard for protected and unprotected routes. Let’s see how we can create one configurable guard that rules them all:

We’ve created a higher-order function that takes a configuration and returns a canMatch function guard. Now, we can use it in our routes:

Follow me on Medium or Twitter to read more about Angular and JS!

--

--

As we learned in my previous article, we can now use the inject() function inside components, directives, and pipes. Here are the reasons I chose it over the constructor for dependency injection. The first thing I noticed is that it is cleaner and more readable:

Using constructor
Using inject()

Next, the provider’s type is automatically inferred:

Auto inferred

Additionally, directiveInject() is used in the compiled code anyway:

Compiled code

Moreover, the param decorator isn’t part of the tc39 spec.

Lastly, the Angular team appears to be heading that way. We can see the inject() usage in the new NgOptimizedImage directive, for example:

NgOptimizedImage

My main concern is consistency. I’d like to see an eslint plugin that helps with that.

Follow me on Medium or Twitter to read more about Angular and JS!

--

--

Netanel Basal

Netanel Basal

A FrontEnd Tech Lead, blogger, and open source maintainer. The founder of ngneat, husband and father.