import { inject } from '@angular/core'; import { CanActivateFn, Router } from '@angular/router'; import { AuthService } from '../services/auth.service'; // Importa AuthService import { map, take } from 'rxjs/operators'; export const authGuard: CanActivateFn = (route, state) => { const authService = inject(AuthService); const router = inject(Router); // Usa l'observable isAuthenticated$ per verificare lo stato return authService.isAuthenticated$.pipe( take(1), // Prende solo il valore corrente e completa map(isAuthenticated => { if (isAuthenticated) { return true; // Utente autenticato, permette accesso } else { // Utente non autenticato, reindirizza al login console.log('AuthGuard: User not authenticated, redirecting to login.'); router.navigate(['/login']); return false; // Blocca accesso alla rotta } }) ); };