728x90

참고영상 : Consumindo uma (GO) API REST com Angular 7 Parte 5 # 29

 

더보기

src/app/user.service.ts 수정

...

export class UserService {
  ...
 
  constructor(private http: HttpClient) {
 
    this.getUsers()
      .subscribe((data) => {

        // 코드 수정
        if(data.length > 0) {
          this.nextUserId = (data[ data.length -1].id +1);
          console.log("ID disponivel : " + this.nextUserId);
        }
      });
  }
 
  public getUsers() {
    ...
  }

  public getUser(id: string) {
    ...
  }

  public postUser(user: any) {
    ...
  }

  public putUser(user: any) {
    ...
  }

  public deleteUser(id: string) {
    ...
  }
}

 

src/app/app.component.ts 수정

...

export class AppComponent {
  ...

  // 코드 추가
  userId = null;  // 현재 지정된 user를 파악하기 위한 변수
  displayForm : boolean = false;  // user 데이터가 비었을때를 대비한 변수
 
  constructor(public service: UserService) {
    this.service.getUsers()
      .subscribe((data) => {
        this.users = data;
        console.log(this.users);

        // 코드 추가
        this.onForm();
      })

    this.service.selectedUser = {
      ...
    };

  }
  
  // 코드 추가 : user 데이터가 1건 이상이면, 테이블 표시
  public onForm() {
    
    if(this.users.length > 0) {
      this.displayForm = true;
      return;
    }

    this.displayForm = false;
  }

  public onSubmit(form: FormGroup) {
 
    console.log(form.value)

    if( form.value.id == null) {
      this.service.postUser(form.value)
        .subscribe((resp) => {
          console.log(resp)

          if(resp["Status"] == 201) {
            this.clearForm();   

            this.service.getUsers()
              .subscribe((data) => {
                this.users = data

                // 코드 추가
                this.onForm();
              });
          }
        });
    } else {
      this.service.putUser(form.value)
        .subscribe((resp) => {
          console.log(resp);

          if(resp["Status"] == 200) {
            // 코드 추가
            this.onForm();

            this.clearForm();
            this.updateList(form.value);
          }
        });
    }
  }

  public onEdit(id: string) {
    ...
  }

  public updateList(user: any) {
    ...
  }

  // 코드 추가 : 호출된 user의 id를 저장
  public deleteConfirm(id: string) {
    this.userId = id;
  }

  // 코드 추가 : 저장된 user의 id를 초기화
  public cancelDelete() {
    this.userId = null;
    console.log("Cancel User Delete");
  }

  // 코드 수정
  public onDelete() { 

    if(this.userId != null) {
      //this.service.deleteUser(id)
      this.service.deleteUser(this.userId)
        .subscribe((resp) => {
          console.log(resp);
  
          if(resp["Status"] == 200) {
  
            //this.users = this.users.filter((user) => user.id != id);
            this.users = this.users.filter((user) => user.id != this.userId);
            
            this.cancelDelete();
            this.onForm();
          }
        });
    }
  }

  public clearForm() {
    ...
  }

}

 

src/app/app.component.html

<div class="container">
  <header>
    ...
  </header>

  <hr>

  <div class="row">
    <div class="col-md-12">
      <h3>Insert User Data</h3>
      <form method="post" #form="ngForm" (ngSubmit)="onSubmit(form)">
        ...
      </form>
    </div>
  </div>

  <br>
  <div class="row">
    <!-- 코드 추가 : user 데이터가 없을때, 안내문 표시-->
    <div clas="col-md-12" *ngIf="!displayForm">
      <p class="alert alert-warning text-center" >
        호출 가능한 User 데이터가 없습니다. <br>
        새로운 User 를 등록해주세요.
      </p>
    </div>

    <!-- 코드 수정 : user 데이터가 1건 이상일 경우 내용 표시-->
    <div clas="col-md-12" *ngIf="displayForm">

      <h3>User Data List</h3>

      <table class="table table-bordered table-hover text-center">
        <thead>
          <tr>
            ...
          </tr>
        </thead>
        <tbody>
          <tr *ngFor="let user of users">
            ...
            <td>
              <!-- 코드 수정 : Call Modal-->
              <button type="button" class="btn btn-sm btn-danger col-block col-lg-8" (click)="onDelete(user.id)" data-bs-toggle="modal" data-bs-target="#exampleModal" (click)="deleteConfirm(user.id)">
                <fa-icon icon="user-minus"></fa-icon>
              </button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>


  <!-- 코드 추가 : Modal -->
  <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="exampleModalLabel">User Data Delete</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close" (click)="cancelDelete()"></button>
        </div>
        <div class="modal-body">
          회원 <strong class="text-danger"> #{{ userId }} </strong> 번의  정보를 삭제 하시겠습니까?
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal" (click)="cancelDelete()">
            Cancle
          </button>

          <button type="button" class="btn btn-danger" data-bs-dismiss="modal" (click)="onDelete()">
            Delete
          </button>
        </div>
      </div>
    </div>
  </div>

  <br>
  <footer>
    ...
  </footer>
</div>

 

Web 결과화면 - No User Data

 

Web 결과화면 - Modal
728x90
Posted by 게으른거북
:
728x90

참고영상 : Consumindo uma (GO) API REST com Angular 7 Parte 5 # 29

 

더보기

src/app/app.module.ts 수정

버튼에 대한 아이콘 추가를 위해 아이콘 Module Import를 진행합니다.

...

// 코드 추가 : icon
import { faUserMinus } from '@fortawesome/free-solid-svg-icons';
import { faUserPlus } from '@fortawesome/free-solid-svg-icons';
import { faUndo } from '@fortawesome/free-solid-svg-icons';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    ...
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {
  
  constructor(library: FaIconLibrary) {
    // 코드 수정
    library.addIcons(faEdit, faUserMinus, faUserPlus, faUndo);
  }
}

 

src/app/user.service.ts 수정

...
export class UserService {
   ...
 
  constructor(private http: HttpClient) {
    ...
  }
 
  public getUsers() {
    ...
  }

  public getUser(id: string) {
    ...
  }

  public postUser(user: any) {
    ...
  }

  public putUser(user: any) {
    ...
  }

  // 코드 추가
  public deleteUser(id: string) {
    return this.http.delete(`${this.Uri}/${id}`);
  }
}

 

src/app/app.component.ts 수정

...

export class AppComponent {
  ...
 
  constructor(public service: UserService) {
    ...
  }

  public onSubmit(form: FormGroup) {
    ...
  }

  public onEdit(id: string) {
    ...
  }
  
  public updateList(user: any) {
    ...
  }

  // 코드 추가 : user 정보 삭제
  public onDelete(id: string) { 

    this.service.deleteUser(id)
      .subscribe((resp) => {
        console.log(resp);

        if(resp["Status"] == 200) {

          this.users = this.users.filter((user) => user.id != id);
        }
      });
  }

  public clearForm() {
    ...
}

 

src/app/app.component.html 수정

<div class="container">
  <header>
    ...
  </header>

  <hr>

  <div class="row">
    <div class="col-md-12">
      <h3>Insert User Data</h3>
      <form method="post" #form="ngForm" (ngSubmit)="onSubmit(form)">
        ...
 
        <div class="form-row">
          <div class="d-grid gap-2 d-md-flex justify-content-md-end">
            <!-- 코드 수정 : icon 추가 -->
            <button class="btn btn-sm btn-block btn-primary col-lg-2" [disabled]="!form.valid" >
              submit &nbsp; <fa-icon icon="user-plus"></fa-icon>
            </button>

            <!-- 코드 수정 : icon 추가 -->
            <button class="btn btn-sm btn-block btn-secondary col-lg-2" (click)="clearForm()">
              clear &nbsp; <fa-icon icon="undo"></fa-icon>
            </button>
          </div>
        </div>
      </form>
    </div>
  </div>

  <br>
  <div class="row">
    <div clas="col-md-12" *ngIf="users">

      <h3>User Data List</h3>
      
      <table class="table table-bordered table-hover text-center">
        <thead>
          <tr>
            <th>Id</th>
            <th>Name</th>
            <th>Email</th>
            <th>Password</th>
            <th>Edit</th>
            <!-- 코드 수정 -->
            <th>Delete</th>
          </tr>
        </thead>
        <tbody>
          <tr *ngFor="let user of users">
            <td>{{ user.id }}</td>
            <td>{{ user.name }}</td>
            <td>{{ user.email }}</td>
            <td>{{ user.password }}</td>
            <td>
              <button type="button" class="btn btn-sm btn-info col-block col-lg-8" (click)="onEdit(user.id)">
                <fa-icon icon="edit"></fa-icon>
              </button>
            </td>
            <!-- 코드 수정 : delete 추가 -->
            <td>
              <button type="button" class="btn btn-sm btn-danger col-block col-lg-8" (click)="onDelete(user.id)">
                <fa-icon icon="user-minus"></fa-icon>
              </button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>

  <br>
  <footer>
    <p class="alert text-center"></p>
  </footer>
</div>

 

Web 결과화면
728x90
Posted by 게으른거북
:
728x90

참고영상 : Consumindo uma (GO) API REST com Angular 7 Parte 4 # 28

 

더보기

폰트 변경

Google Font (링크)

Google Font 페이지

 

index.html 에 추가

<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Montserrat" rel="stylesheet">

 

src/app/app.component.css 에 추가

.container {
    font-family: 'Montserrat', sans-serif;
}

 

src/app/app.service.ts 수정

...

export class UserService {
  ...
 
  constructor(private http: HttpClient) {
    ...
  }
 
  public getUsers() {
    ...
  }

  public getUser(id: string) {
    ...
  }

  public postUser(user: any) {
    ...
  }

  // 코드 추가
  public putUser(user: any) {

    let data = {
      "id"        :   user.id,
      "name"      :   user.name,
      "email"     :   user.email,
      "password"  :   user.password
    };

    return this.http.put(`${this.Uri}/${user.id}`, JSON.stringify(data));
  }
}

 

src/app/app.component.ts 수정

...

export class AppComponent {
  ...
 
  constructor(public service: UserService) {
    ...
  }

  public onSubmit(form: FormGroup) {
 
    console.log(form.value)

    if( form.value.id == null) {
      this.service.postUser(form.value)
        .subscribe((resp) => {
          console.log(resp)

          if(resp["Status"] == 201) {
            this.clearForm();   // 코드 추가
            this.service.getUsers()
              .subscribe((data) => this.users = data);
          }
        });
    } else {
      // 코드 추가 : user 데이터 수정
      this.service.putUser(form.value)
        .subscribe((resp) => {
          console.log(resp);

          if(resp["Status"] == 200) {
            this.clearForm();
            this.updateList(form.value);
          }
        });

    }
  }

  // 코드 추가 : user 데이터를 Form에 전달
  public onEdit(id: string) {

    this.service.getUser(id)
      .subscribe((data) => {
        this.service.selectedUser = data;
      });
  }
  
  // 코드 추가 : 테이블 내 user 데이터 갱신
  public updateList(user: any) {
    for(var i = 0; i < this.users.length; i++) {
      if(user.id == this.users[i].id) {
        this.users[i] = user;
        return;
      }
    }
  }

  // 코드 추가 : Form 비우기
  public clearForm() {
    this.service.selectedUser = {
      "id": null,
      "name": '',
      "email": '',
      "password": ''
    };
  }
}

 

Web 결과화면
728x90
Posted by 게으른거북
:
728x90

참고영상 : Consumindo uma (GO) API REST com Angular 7 Parte 4 # 28

 

참고 사이트 : angular-fontawesome (링크)

NPM - angular fontawesome

 

시작하기에 앞서, 영상에서는 HTML <head> 태그에 link를 추가하지만

저는 귀찮은 방법이지만 angular를 직접 활용 사용하겠습니다.

 

더보기

NPM Install

npm install @fortawesome/fontawesome-svg-core
npm install @fortawesome/free-solid-svg-icons
npm install @fortawesome/angular-fontawesome

 

src/app/app.modules.ts 수정

...

// 코드 추가
import { FontAwesomeModule } from '@fortawesome/angular-fontawesome';
import { FaIconLibrary } from '@fortawesome/angular-fontawesome';
import { faEdit } from '@fortawesome/free-solid-svg-icons';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    ...

    // 코드 추가
    FontAwesomeModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {
  
  // 코드 추가
  constructor(library: FaIconLibrary) {
    library.addIcons(faEdit);
  }
}

 

src/app/app.component.html 수정

<div class="container">
  <header>
    ...
  </header>
  
  <hr>
  
  <div class="row">
    ...
  </div>

  <br>
  <div class="row">
    <div clas="col-md-12" *ngIf="users">

      <h3>User Data List</h3>
      
      <!-- table의 class 추가 : text-center -->
      <table class="table table-bordered table-hover text-center">
        <thead>
          <tr>
            <th>Id</th>
            <th>Name</th>
            <th>Email</th>
            <th>Password</th>
            <th>Edit</th>	<!-- 코드 추가 -->
          </tr>
        </thead>
        <tbody>
          <tr *ngFor="let user of users">
            <td>{{ user.id }}</td>
            <td>{{ user.name }}</td>
            <td>{{ user.email }}</td>
            <td>{{ user.password }}</td>
            <!-- 코드 추가 -->
            <td>
              <button type="button" class="btn btn-sm btn-info col-block col-lg-8">
                <fa-icon icon="edit"></fa-icon>
              </button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</div>

<fa-icon icon="edit"></fa-icon>

app.module.ts에서 liabray 정의한 아이콘을 사용하는 태그

 

Web 결과화면

 

728x90
Posted by 게으른거북
:
728x90

참고영상 : Consumindo uma (GO) API REST com Angular 7 Parte 3 # 27

 

더보기

src/app/user.service.ts 수정

...
export class UserService {
  ...
 
  constructor(private http: HttpClient) { ... }
 
  public getUsers() { ... }

  // 코드 추가
  public getUser(id: string) {
    // 특정 user의 데이터를 Get
    return this.http.get(`${this.Uri}/${id}`);
  }

  // 코드 추가
  public postUser(user: any) {

    user.id = this.nextUserId;

    // form을 통해 전달 받은 값을 저장
    let data = {
      "id"        :   user.id,
      "name"      :   user.name,
      "email"     :   user.email,
      "password"  :   user.password
    };
	
    // data에 저장된 데이터를 JOSN 형식으로 변경하여,
    // Uri로 Post 진행
    // Return 값은 Response가 반환됨
    return this.http.post(this.Uri, JSON.stringify(data));
  }
}

 

src/app/app.component.ts 수정

...

export class AppComponent {
  ...
 
  constructor(public service: UserService) { ... }

  public onSubmit(form: FormGroup) {
 
    console.log(form.value)

    // 코드 추가
    if( form.value.id == null) {
      // postUser 서비스 함수 이용
      this.service.postUser(form.value)
        .subscribe((resp) => {
          console.log(resp)

          // Response를 통해 전달 받은 Status가 201일 경우,
          // user 데이터를 갱신
          if(resp["Status"] == 201) {
            this.service.getUsers()
              .subscribe((data) => this.users = data);
          }
        })
    }
  }
}

 

src/app/app.component.html 수정

<div class="container">
  <header>
    ...
  </header>

  <hr>

  <div class="row">
    <div class="col-md-12">
      <h3>Insert User Data</h3>
      <form method="post" #form="ngForm" (ngSubmit)="onSubmit(form)">
 
        <input type="hidden" name="id" [(ngModel)]="service.selectedUser.id">
        <div class="form-group">
          <label for="name">Name : </label>
          <!-- 입력 여부를 파악하기 위한 구분자 required 추가 -->
          <input type="text" name="name" id="name" class="form-control" placeholder="insert your name" [(ngModel)]="service.selectedUser.name" required >
        </div> 
        <div class="form-group">
          <label for="email">Email : </label>
          <!-- 입력 여부를 파악하기 위한 구분자 required 추가 -->
          <input type="text" name="email" id="email" class="form-control" placeholder="insert your email" [(ngModel)]="service.selectedUser.email" required>
        </div>
        <div class="form-group">
          <label for="password">Password : </label>
          <!-- 입력 여부를 파악하기 위한 구분자 required 추가 -->
          <input type="text" name="password" id="password" class="form-control" placeholder="insert your password" [(ngModel)]="service.selectedUser.password" required>
        </div>
 
        <div class="form-row">
          <div class="d-grid gap-2 d-md-flex justify-content-md-end">
            <!-- [disabled]="!form.valid : 미입력한 항목(required)이 있을 경우, disable 처리 -->
            <button class="btn btn-sm btn-block btn-primary col-lg-2" [disabled]="!form.valid" >submit</button>
            <button class="btn btn-sm btn-block btn-secondary col-lg-2">clear</button>
          </div>
        </div>
      </form>
    </div>
  </div>

  <br>
  <div class="row">
    ...
  </div>
  
</div>

 

Web 결과화면
728x90
Posted by 게으른거북
: