Creating a role-based application in Angular involves several key steps, including setting up Angular routes, services for managing roles and authentication, and guards to protect routes based on user roles. While I can’t provide a complete demo application within this format, I can guide you through the process of creating a simple role-based application in Angular 17. This guide will walk you through setting up Angular, creating services for role management, implementing route guards, and configuring routes based on roles.
Step 1: Setting up Angular Environment
- Install Angular CLI: First, make sure you have Node.js installed. Then, install the Angular CLI globally using npm:
npm install -g @angular/cli
- Create a New Angular Project: Generate a new Angular project using the CLI:
ng new role-based-app
- Navigate to Your Project: Change directory to your new project:
cd role-based-app
Step 2: Creating a Role Service
- Generate a Role Service: This service will manage user roles.
ng generate service services/role
- Implement Role Logic: In your
role.service.ts, implement basic role management logic. For simplicity, you might just hard-code some roles for demonstration purposes.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class RoleService {
// Example roles
roles = ['admin', 'user'];
constructor() { }
// Check if the user has a specific role
hasRole(role: string): boolean {
return this.roles.includes(role);
}
}
Step 3: Implementing Authentication Service
- Generate an Authentication Service: This service will handle user authentication.
ng generate service services/auth
- Implement Authentication Logic: For a demo, you can simulate authentication.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class AuthService {
isAuthenticated = false;
constructor() { }
// Simulate a login
login(): void {
this.isAuthenticated = true;
}
// Simulate a logout
logout(): void {
this.isAuthenticated = false;
}
// Check if the user is authenticated
getIsAuthenticated(): boolean {
return this.isAuthenticated;
}
}
Step 4: Creating Route Guards
- Generate a Guard: This guard will protect routes based on roles.
ng generate guard guards/role
- Implement Guard Logic: Use the
RoleServiceto check for roles and theAuthServicefor authentication status.
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService } from '../services/auth.service';
import { RoleService } from '../services/role.service';
@Injectable({
providedIn: 'root'
})
export class RoleGuard implements CanActivate {
constructor(private authService: AuthService, private roleService: RoleService) {}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
const requiredRole = next.data.requiredRole;
return this.authService.getIsAuthenticated() && this.roleService.hasRole(requiredRole);
}
}
Step 5: Configuring Routes
- Setup Routes with Guards: In your
app-routing.module.ts, configure your routes to use theRoleGuardand specify roles required for each route.
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { RoleGuard } from './guards/role.guard';
const routes: Routes = [
{
path: 'admin',
loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule),
canActivate: [RoleGuard],
data: { requiredRole: 'admin' }
},
// Add more routes here
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
Step 6: Running the Application
Finally, run your Angular application:
ng serve
This setup demonstrates a basic structure for a role-based Angular application. You’ll need to expand upon this with actual user authentication logic, dynamic role management, and more complex route guards based on your specific requirements. For a complete application, consider adding user registration, role assignment functionality, and a backend to persist user data and roles.
