ЁЯЫбя╕П

Angular Guards

Jul 29, 2024

Lecture Notes: Angular Guards

Introduction

  • Welcome to the channel and group for learning and live coding sessions.
  • Encouragement to subscribe and join a community of over 1000 members.
  • Resources available: project ideas, flow diagrams, API documentation, etc.

Key Concept: Angular Guards

  • Definition: Guards are similar to the concept of тАШguardтАЩ in English, serving the same protective function.
  • Types of Guards:
    • There are approximately 5 to 6 different types of guards in Angular.
    • Specific focus on Can Activate Guard in this session.

Previous Session Recap

  • Covered login functionality related to guards.
  • Importance of verifying whether a user is logged in before accessing certain routes.

Overview of Can Activate Guard

  • Purpose: Prevent unauthenticated users from accessing protected routes.
  • Scenario explained:
    • If a user knows a route (like /dmps), they might attempt to access it even if not logged in, which shouldn't happen.
    • Can Activate Guard prevents such scenarios by checking user authentication status before route activation.

Creating a Guard

  1. Create Guard:
    • Create a folder named service if not done already, then open a new terminal in that folder.
    • Command: ng generate guard AuthenticationGuard.
    • Specify the type of guard: CanActivate when prompted.
  2. Structure:
    • New guard created as an arrow function (this is the Angular update from version 15).
    • Set up the guard in the routes where protection is required.
    • E.g., only authenticated users should access the data binding route.

Implementation Logic

  • In the login component, check local storage for user credentials to determine login status.
    • If user data present, return true (access granted).
    • If not, redirect to login page and return false (access denied).

Steps for Implementation

  1. Check local storage for user data: let loggedUser = localStorage.getItem('key'); if (loggedUser != null) { return true; } else { this.router.navigate(['login']); return false; }

Testing the Guard

  • Initially no user data in local storage should redirect to login.
  • After logging in, check routes to ensure guard properly activates, granting access.
  • Emphasize that once logged out (clearing local storage), attempting to access protected routes should redirect to login.

Conclusion

  • Importance of guards in Angular for route protection.
  • Next sessions will explore more advanced scenarios, such as role-based route access.
  • Reminder to subscribe, like, and engage with the content.

Key Takeaways

  • Guards are essential for protecting routes in Angular applications.
  • Can Activate Guard specifically ensures only authenticated users can access certain routes.
  • Local storage plays a crucial role in tracking user login state.
  • Advanced implementations may include role checks and additional conditions.