DEV Community

Cover image for 👮🛡️ Let's Navigate the Angular Playground with Route Guards
Ahmed Murtaza
Ahmed Murtaza

Posted on • Edited on

👮🛡️ Let's Navigate the Angular Playground with Route Guards

Imagine we are in a big, exciting playground filled with different areas to explore. Angular route guards are like our friendly guides, making sure we have fun while keeping things safe and sound. Let's discuss what these route guards have to offer, helping us navigate our playground safely and securely.

Here is the sneak peak of when and where we use Route Guards based on different scenarios:

Image description

1. Can I Come In? - The CanActivate Guard

You know that feeling when you want to enter a special play zone, but there is a nice adult checking if you are allowed? Thats what CanActivate does in Angular. It ensures that you have the green light to access a particular route. It's perfect for scenarios like letting only loggedin users into the VIP section of our play area.

Image description

2. Ready to Leave? - The CanDeactivate Guard

Sometimes, we need to check if you're ready to leave an area. The CanDeactivate guard is like asking, "Are you sure you want to leave? Did you collect all your toys?" It comes in handy when you want to make sure users don't accidentally leave a page with unsaved changes or partially filled form. So basically this protects the route, however it does not prevent that module from loading.

Image description

Image description

3. Show Your Badge - The CanLoad Guard

Imagine some areas in the playground require a special permission. Angular's CanLoad guard checks if you have the right permission before loading an entire section. This is super useful for lazy-loaded modules, ensuring that only the cool kids with the proper permissions can access certain parts of our application.

Image description

In comparision to CanActivate guard, CanLoad protects the route completely. Such as lazy loading the module and also protects all the routes associated with that module. If the user is unauthorized then this canLoad guard avoids additional loading of auth Modules

4. Checking Your Bag - The Resolve Guard

Before you enter a play zone, it's always a good idea to check if you have everything you need. Resolve guard is like looking into your bag to make sure you are prepared. It lets you fetch data or do some last minute setup before the route is activated.

Image description

Image description

Image description

And there you have it, a playful introduction to Angular route guards!! They are your trusty companions, making sure your journey through the Angular playground is smooth, secure and full of excitement.

Happy coding folks! 🚀

Top comments (0)