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 |