라우팅을 이용한 접근권한 처리 updated_at: 2024-12-15 04:04

CanActivate

Auth등 접근 권한을 설정하기에 유용합니다.

CanActivateGuard

  • auth-guard.service.ts
import { Injectable } from '@angular/core';
import { Router, CanActivate } from '@angular/router';
import { AuthService } from './auth.service';
@Injectable()
export class AuthGuardService implements CanActivate {
  constructor(
    private auth: AuthService,
    private router: Router
  ) {}

  canActivate(): boolean {
    if (this.auth.isAuthenticated()) {
      this.router.navigate(['/auth/account']);
      return false;
    }
    return true;
  }
}

module.ts

import { AuthGuardService } from './auth-guard.service';
@NgModule({
    providers: [AuthGuardService]
})

app.routes.ts

import { AuthGuardService } from './auth-guard.service';
export const appRoutes: Routes = [
    ......................
  { path: 'product', component: ProductComponent, canActivate : [AuthGuardService] },

];

로그인 후 리다이렉트

import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { AuthService } from './auth.service';
@Injectable()
export class AuthGuard implements CanActivate {
  constructor(
    private auth: AuthService,
    private router: Router
  ) {}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    let url: string = state.url;
    if (this.auth.isAuthenticated()) {
      if (url) {
        this.router.navigate([url]);
      } else {
        this.router.navigate(['/']);
      }
      return false;
    }
    return true;
  }
}
평점을 남겨주세요
평점 : 5.0
총 투표수 : 2

질문 및 답글