0 votes
in Angular by
What is the role of route guards in Angular, and how can they be used to implement authorization?

1 Answer

0 votes
by
Route guards in Angular are responsible for controlling access to specific routes based on user roles or permissions. They act as middleware, deciding whether a user can navigate to a particular route or not.

To implement authorization using route guards, follow these steps:

1. Create a custom guard by implementing the CanActivate interface.

2. Inject any required services, such as an authentication service, into the guard’s constructor.

3. Implement the canActivate() method, which returns either true (allowing navigation) or false (denying navigation). Use the injected services to determine if the user has the necessary permissions.

4. Register the custom guard in the AppModule providers array.

5. Add the custom guard to the desired route(s) in the AppRoutingModule using the ‘canActivate’ property.

Example of a custom route guard:

import { Injectable } from '@angular/core';

import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';

import { AuthService } from './auth.service';

@Injectable()

export class AuthGuard implements CanActivate {

  constructor(private authService: AuthService) {}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {

    return this.authService.isAuthenticated();

  }

}

Related questions

0 votes
asked Jan 6, 2020 in Angular by sharadyadav1986
0 votes
asked Dec 31, 2023 in Angular by DavidAnderson
...