zoaseo
To Infinity And Beyond
zoaseo
전체 방문자
오늘
어제
  • 분류 전체보기 (763)
    • 개발이 좋아서 (381)
      • SAP가 좋아서 (3)
      • Java가 좋아서 (42)
      • Spring이 좋아서 (50)
      • JPA가 좋아서 (0)
      • QueryDSL이 좋아서 (26)
      • Docker가 좋아서 (7)
      • Redis가 좋아서 (7)
      • AWS가 좋아서 (5)
      • CI/CD가 좋아서 (6)
      • Troubleshooting이 좋아서 (4)
      • Kotlin이 좋아서 (7)
      • SQL이 좋아서 (6)
      • HTTP가 좋아서 (21)
      • JavaScript가 좋아서 (30)
      • TypeScript가 좋아서 (6)
      • Vue가 좋아서 (21)
      • Flutter가 좋아서 (61)
      • React가 좋아서 (20)
      • Redux(React)가 좋아서 (2)
      • Angular가 좋아서 (22)
      • HTML이 좋아서 (9)
      • CSS가 좋아서 (15)
      • PHP가 좋아서 (9)
      • Illustrator가 좋아서 (2)
    • 노력이 좋아서 (169)
    • 결과물이 좋아서 (14)
    • 코딩연습이 좋아서 (168)
      • 이론이 좋아서 (62)
      • SQL이 좋아서 (90)
    • 유용한 사이트가 좋아서 (28)
    • Github (2)

인기 글

티스토리

hELLO · Designed By 정상우.
zoaseo
개발이 좋아서/Angular가 좋아서

Angular - 튜토리얼13_가드(인터셉터)

Angular - 튜토리얼13_가드(인터셉터)
개발이 좋아서/Angular가 좋아서

Angular - 튜토리얼13_가드(인터셉터)

2022. 9. 29. 16:07

1)

ng g guard 이름

ng g guard auth

 

2)

board.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-board',
  templateUrl: './board.component.html',
  styleUrls: ['./board.component.css']
})
export class BoardComponent implements OnInit {

  constructor() { }

  ngOnInit(): void {
  }

}

login.component.html

<input type="text" placeholder="id입력" [(ngModel)]="id" />
<input type="text" placeholder="password입력" [(ngModel)]="passwd" />
<input type="button" value="로그인" (click)="login()" />

login.component.ts

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { AskService } from '../ask.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  id!: string;
  passwd!: string;

  constructor(private service : AskService, private rout : Router) {
    // 생성자에 private를 붙여서 의존성을 주입받으면 글로벌하게 사용가능합니다.
    // private가 있으므로 다른 컴포넌트나 html파일에서는 접근할 수 없습니다.
   }

  ngOnInit(): void {
  }
  login() { // subscribe을 통해 구독하여 콜백행위를 하게 하였습니다.
    this.service.tryToLogin({id: this.id, passwd : this.passwd}).subscribe((arg:any)=>{
      console.log(arg);
      if(arg.status == true){
        alert('로그인 성공!');
        this.rout.navigate(['/board']); // board 컴포넌트로 이동!
      }
    })
    console.log(this.id, this.passwd);
  }
}

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: '<router-outlet></router-outlet>',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'FrontEnd3';
}

app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent } from './app.component';
import { LoginComponent } from './login/login.component';
import { BoardComponent } from './board/board.component';
import { RouterModule,Routes } from '@angular/router';
import { AuthGuard } from './auth.guard';
import { FormsModule } from '@angular/forms';

const router : Routes = [ // 라우팅
  {path : 'login' , component : LoginComponent},
  {path : 'board' , component : BoardComponent, canActivate:[AuthGuard]}, // 가드추가
  {path : '', redirectTo : '/login', pathMatch : 'full'}
]

@NgModule({
  declarations: [
    AppComponent,
    LoginComponent,
    BoardComponent
  ],
  imports: [
    BrowserModule,
    RouterModule.forRoot(router,{enableTracing:false, useHash: true}), // useHash는 나중에 요긴하게 쓰입니다.
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

ask.service.ts

import { Injectable } from '@angular/core';
import { Observable, BehaviorSubject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class AskService {

  // 저장소(나중에 데이터베이스 서버)
  private readonly storage = {
    id : 'admin',
    passwd : '1234'
  }
  constructor() { }

  // 로그인 시도 함수
  tryToLogin(param:any){
    return new Observable(arg=>{ // 관측대상 생성
      if(param.id == this.storage.id && param.passwd == this.storage.passwd){
        arg.next({status: true}); // 성공
        localStorage.setItem('status','true'); // 로컬저장소에 저장!
      }else {
        arg.next({status: false, reason : 'wrong information'}) // 실패
      }
      arg.complete();
    });
  }

  // 가드가 구독하는 대상
  readonly isLogged: BehaviorSubject<boolean> = new BehaviorSubject(false);

  // 로그인이 되었느지 확인하는 함수
  isLogin() : void{
    if(localStorage.getItem('status') == 'true'){ // 저장소에 로그인 정보가 있는지 확인
      this.isLogged.next(true);
    }else {
      this.isLogged.next(false);
    }
  }
}

auth.guard.ts

import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, RouterStateSnapshot, UrlTree } from '@angular/router';
import { Observable } from 'rxjs';
import { AskService } from './ask.service';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {

  private status : boolean = false; // 글로벌 변수

  constructor(private serv : AskService){
    serv.isLogged.subscribe(result=>{ // 로그인 여부가 담길 대상을 구독합니다!
      console.log('서버에 물어보고 온 결과', result);
      this.status = result; // 결과값을 업데이트
    })
  }

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree{
      this.serv.isLogin(); // 로그인되었는지 확인!
      return this.status; // 요기를 바꿉니다!
    }
  }

3)

'개발이 좋아서 > Angular가 좋아서' 카테고리의 다른 글

Angular - 로그인 UI 구현(service, guard)  (0) 2022.09.30
Angular - 회원가입 UI 구현  (0) 2022.09.30
Angular - 튜토리얼12_라우팅  (0) 2022.09.29
Angular - 튜토리얼11_Observable  (0) 2022.09.29
Angular - 튜토리얼10_데이터 공유(Share, Inject)  (0) 2022.09.29

    티스토리툴바

    개인정보

    • 티스토리 홈
    • 포럼
    • 로그인

    단축키

    내 블로그

    내 블로그 - 관리자 홈 전환
    Q
    Q
    새 글 쓰기
    W
    W

    블로그 게시글

    글 수정 (권한 있는 경우)
    E
    E
    댓글 영역으로 이동
    C
    C

    모든 영역

    이 페이지의 URL 복사
    S
    S
    맨 위로 이동
    T
    T
    티스토리 홈 이동
    H
    H
    단축키 안내
    Shift + /
    ⇧ + /

    * 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.