Permission Service
The PermissionService is a core service in an Angular application designed to manage user permissions. It provides methods to retrieve, set, and validate permissions, as well as an observable stream to reactively monitor permission changes. This service plays a critical role in implementing role-based access control (RBAC) and securing the application’s UI and functionality.
Features
Permission Storage and Management:
Stores the user's permissions and provides methods to update them.
Observable Permissions:
Exposes permissions as an
Observablestream (permissions$), enabling reactive updates in components.
Validation:
Provides a method to check if a user has a specific permission (
hasPermission).
Integration with HTTP:
Extends
CommonHttpService, allowing for potential integration with APIs for fetching permissions.
Methods
1. getPermissions(): Observable<[ { permissions: string[] } ]>
Description:
Fetches the current permissions from an API or other sources.
Returns an observable containing an array of objects, each with a
permissionsproperty.
2. setPermissions(permissions: string[]): void
Description:
Updates the permissions stored in the service.
Also updates the
permissions$observable stream, ensuring that components react to changes.
Parameters:
permissions: An array of permission strings to set.
3. hasPermission(permission: string): boolean
Description:
Checks if the user has a specific permission.
Parameters:
permission: The permission string to check.
Returns:
trueif the permission exists, otherwisefalse.
Route Guards with canActivate
Angular Router provides several guard methods to control route navigation and access. These guards can be used with PermissionService to implement permission-based route protection. The four main guard methods are:
1. canActivate
Description:
Controls whether a route can be activated. This guard is executed before navigating to a route and can be used to check user permissions.
When to Use:
To protect routes that require specific permissions
To check authentication before allowing access
To redirect users based on their permissions
Implementation Example:
Usage in Routes:
Example from Codebase:
File: src/app/dashboard/dashboard.routes.ts (line 18)
Last updated