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!



Netanel Basal

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