Код IT
← Каталог

Справочник по Angular — 26.3. Шаблон guard

Фрагмент из «Справочник по Angular»: 26.3. Шаблон guard.

typescript javascriptencyclopedia3-ecosystem-2-frontend-frameworks-3-angular-291 embed URL статья в энциклопедии
TypeScript main.ts

import { Injectable } from '@angular/core';
import { CanActivateFn } from '@angular/router';
import { map } from 'rxjs';
import { AuthService } from './auth.service';

export const authGuard: CanActivateFn = () => {
  const authService = inject(AuthService);
  return authService.isAuthenticated$.pipe(map(isAuth => isAuth || redirectToLogin()));
};

function redirectToLogin(): boolean {
  // перенаправление через Router
  inject(Router).navigate(['/login']);
  return false;
}

import { Injectable } from '@angular/core';
import { CanActivateFn } from '@angular/router';
import { map } from 'rxjs';
import { AuthService } from './auth.service';

export const authGuard: CanActivateFn = () => {
  const authService = inject(AuthService);
  return authService.isAuthenticated$.pipe(map(isAuth => isAuth || redirectToLogin()));
};

function redirectToLogin(): boolean {
  // перенаправление через Router
  inject(Router).navigate(['/login']);
  return false;
}