>  기사  >  웹 프론트엔드  >  Guard Dans Angular

Guard Dans Angular

WBOY
WBOY원래의
2024-07-19 04:29:39693검색

Image description

소개

이 글에서는 Angular 17에서 가드를 사용하는 방법을 살펴보겠습니다. 가드를 사용하면 경로를 보호하고 특정 경로에 대한 액세스를 허용하기 전에 특정 조건을 확인할 수 있습니다.

기능성 가드란 무엇입니까?

Angular의 기능적 가드는 경로 탐색을 가로채고 잠재적으로 차단하는 데 사용되는 기능입니다. Angular 17에서는 CanActivateFn을 사용하여 기능적 가드를 생성합니다.

코드 예

다음은 기능적인 authGuard의 예입니다.

import { CanActivateFn } from '@angular/router';
import { inject } from '@angular/core';
import { Router } from '@angular/router';
import { AuthService } from './auth.service';

export const authGuard: CanActivateFn = (route, state) => {
  const authService = inject(AuthService);
  const router = inject(Router);

  if (authService.isLoggedIn()) {
    return true;
  } else {
    router.navigate(['/login']);
    return false;
  }
};

가드 사용

이 가드를 사용하려면 ProvideRouter 및 withGuards를 사용하여 라우팅 모듈에서 이를 구성해야 합니다.

import { bootstrapApplication } from '@angular/platform-browser';
import { provideRouter, withGuards } from '@angular/router';
import { AppComponent } from './app/app.component';
import { authGuard } from './app/guards/auth.guard';

const routes = [
  { path: 'protected', component: ProtectedComponent, canActivate: [authGuard] }
];

bootstrapApplication(AppComponent, {
  providers: [
    provideRouter(routes, withGuards())
  ]
}).catch(err => console.error(err));

코드 설명

  • CanActivateFn: 보호 기능을 나타내는 유형
  • inject: 서비스와 같은 종속성을 주입하는 기능입니다.
  • 라우터: 다른 경로로 안내해주는 라우팅 서비스
  • authGuard: 사용자가 인증되었는지 확인하는 가드 기능입니다.

결론

Angular 17의 기능 가드는 경로를 보호하고 권한을 관리하는 유연하고 강력한 방법을 제공합니다. 이는 인증 및 액세스 제어와 같은 작업에 특히 유용합니다.

자세한 내용은 가드에 대한 공식 Angular 문서를 참조하세요.【20†source】【22†source】【23†source】.

위 내용은 Guard Dans Angular의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.