728x90

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

 

더보기

위 방법이 마음에 안들어 다른 사이트를 참고하였습니다.

참고사이트 : NPM_ngx-toastr (링크)

 


NPM 설치

npm install ngx-toastr --save
npm install @angular/animations --save

 

src/style.css 수정

@import '~ngx-toastr/toastr.css';

 

src/app/app.module.ts 수정

...

// 코드 추가
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { ToastrModule } from 'ngx-toastr';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    FormsModule,
    FontAwesomeModule,

    // 코드 추가
    BrowserAnimationsModule,
    ToastrModule.forRoot()
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {
  ...
}

 

src/app/app.component.ts 수정

...

// 코드 추가
import { ToastrService } from 'ngx-toastr';

@Component({
  ...
})
export class AppComponent {
  ...
 
  // 코드 수정
  //constructor(public service: UserService) {
  constructor(public service: UserService, private toastr: ToastrService) {
    ...
  }
  
  // 코드 추가 : toastr을 간편하게 쓰기 위한 함수
  public onToastr(service: string, title: string, message: string) {
    switch(service) {
      case "success": {
        this.toastr.success(message, title, {timeOut: 2000});
        break;
      }
      case "info": {
        this.toastr.info(message, title, {timeOut: 2000});
        break;
      }
      case "warning": {
        this.toastr.warning(message, title, {timeOut: 2000});
        break;
      }
      case "error": {
        this.toastr.error(message, title, {timeOut: 2000});
        break;
      }
      default: {
        console.log("Toast Error");
        break;
      }
    }
  }

  public onForm() {
    ...
  }

  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.onToastr("success", "Data Insert", "새로운 User가 등록되었습니다.");

                this.users = data
                this.onForm();
              });
          }
        });
    } else {
      
      this.service.putUser(form.value)
        .subscribe((resp) => {
          console.log(resp);

          if(resp["Status"] == 200) {
            // 코드 추가
            this.onToastr("info", "Data Edit", "User 정보가 수정되었습니다.");

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

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

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

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

  public cancelDelete() {
    ...
  }

  public onDelete() { 

    if(this.userId != null) {
      this.service.deleteUser(this.userId)
        .subscribe((resp) => {
          console.log(resp);
  
          if(resp["Status"] == 200) {
            // 코드 추가
            this.onToastr("error", "Data Delete", "User 정보가 삭제되었습니다.");

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

  public clearForm() {
    ...
}

 

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 게으른거북
:
728x90

참고영상 : Como Programar uma API REST em Golang Parte 7 - HANDLERS CORS - Iniciando

 

더보기

프로젝트 환경 세팅

node.js, npm, angular를 기본적으로 세팅한 상태에서 진행하겠습니다.

cmd 창에서 angular 프로젝트를 myapp 으로 생성.

cd workspace/angular
ng new myapp

 

No -> No -> CSS 선택

cmd - angular 프로젝트 설정

 

Angular 테스트

폴더로 이동하여, 실행 명령어를 입력해줍니다.

cd myapp
ng serve --open

 

잠시 기다려 주면, 아래와 같이 실행화면이 띄워집니다.

웹페이지가 실행이 안될 경우, localhost:4200 을 들어가시면 됩니다.

angular 실행화면
728x90
Posted by 게으른거북
: