[[oktatas:web:angular|< Angular]] ====== Angular - Útvonalak védelme ====== * **Szerző:** Sallai András * Copyright (c) Sallai András, 2023 * Licenc: [[https://creativecommons.org/licenses/by-sa/4.0/|CC Attribution-Share Alike 4.0 International]] * Web: https://szit.hu ===== Guard ===== Az egyes útvonalak védelméről a guard nevű eszközzel tudunk gondoskodni. A shared nevű könyvtárban fogom létrehozni (nem kötelező itt létrehozni): ng g guard shared/auth Létrehozáskor rákérdez milyen típusokat szeretnénk: >(*) CanActivate ( ) CanActivateChild ( ) CanDeactivate ( ) CanLoad A szóközzel jelölhetek ki, a le és fel billentyűvel választhatok, az Enter billentyűre továbblép. Szükségünk van egy metódusra, ami megmondja, hogy azonosítva vagyunk-e. isLoggedIn() { if (localStorage.getItem('currentUser') === null) { return false; } return true; } import { Injectable } from '@angular/core'; import { ActivatedRouteSnapshot, CanActivate } from '@angular/router'; import { Router, RouterStateSnapshot, UrlTree } from '@angular/router'; import { Observable } from 'rxjs'; import { AuthService } from './auth.service'; @Injectable({ providedIn: 'root' }) export class AuthGuard implements CanActivate { constructor( private auth: AuthService, private router: Router ) {} canActivate() route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable | Promise | boolean | UrlTree { if( this.auth.isLoggedIn() ) { return true; } this.router.navigate(['login']); return false; } } const routes: Routes = [ { path: 'employees', component: EmployeeComponent, canActivate: [AuthGuard] }, {path: '**', component: NopageComponent} ];