Member-only story

Testing Your Functional Route Guards (Angular)

Daniel Kreider
3 min readNov 19, 2024

--

Photo by AbsolutVision on Unsplash

Angular recently got a new feature called functional route guards.

Functional guards were a bold move away from the Typescript class-style route guards to just a simple function.

And I think it was a great idea!

But one of the down-sides of this new change was that the functional route guards do not have a constructor to inject Angular dependencies.

Which raised a bit of a ruckus in this GitHub issue of folks complaining about the constructor being gone.

Instead, we use the inject function

Since the constructor no longer exists we have to instead use the inject function to inject our dependencies.

Something like this.

import { inject } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivateFn, Router, RouterStateSnapshot, UrlTree } from '@angular/router';

export const appGuard: CanActivateFn = (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => {
const router = inject(Router);
const token = localStorage.getItem("token");
if (token) {
return true;
}
return…

--

--

Responses (1)