DEV Community

Paweł Fraś
Paweł Fraś

Posted on

Angular 17 ✨mapToCanActivate✨: Your Class Guards' Best Friend

When you're updating your Angular app to version 16, you might notice that the CanActivate interface is now deprecated. If you're thinking about changing your class guards to functional ones (or injecting the class in a wrapper function like this:

() => inject(MyGuard).canActivate()
Enter fullscreen mode Exit fullscreen mode

here's the deal - Angular 17 will probably come with a handy function called mapToCanActivate that should let you stick with your class guards as they are. Let's check out this example:

@Injectable({providedIn: 'root'})
export class AdminGuard {
  canActivate() {
    return true;
  }
}

const route: Route = {
  path: 'admin',
  canActivate: mapToCanActivate([AdminGuard]),
};
Enter fullscreen mode Exit fullscreen mode

The function accepts an array as an argument, allowing you to pass all your guards for a specific route without having to create a separate wrapper for each one.

It seems like you can delay the refactoring for a bit and concentrate on your business requirements! 🙂

source: https://next.angular.io/api/router/mapToCanActivate

Top comments (0)