---
# System prepended metadata

title: 中繼器1
tags: [CTBC-Lab4]

---

# 中繼器1
###### tags: `CTBC-Lab4`

```typescript
// 函式
  // {studentId:number,studentName:string,studentScore:number,gradeId:number,gradeName:string,gradeHowMany:number}
  onUpdateStudent(updateForm: any) {
    console.log("updateForm內容如下 \n", updateForm);
    const URLGetOne = 'http://localhost:8080/api/student/' + updateForm.studentId;
    console.log(URLGetOne);
    this.http.get<Student>(URLGetOne).subscribe(
      (data) => {
        console.log("查看gradeId : ", updateForm.gradeId);
        // 學生
        data.studentId = updateForm.studentId;
        data.studentName = updateForm.studentName;
        data.studentScore = updateForm.studentScore;
        // 年級
        data.gradeBean.gradeId = updateForm.gradeId;
        data.gradeBean.gradeName = updateForm.gradeName;
        data.gradeBean.gradeHowMany = updateForm.gradeHowMany;

        const URLPost = 'http://localhost:8080/api/student';
        this.http.post(URLPost, data).subscribe(
          (data2) => {
            this.onGetAllStudent();
            console.log('修改成功, 結果是:', data2);
          });
      },
      (error) => {
        console.error('GetAll failed');
        console.error(error);
      });
  }
```

---

```java
// 取出舊的一筆
StudentBean ori = studentBeanRepository.findById(oneStudent.getStudentId()).get(); 
// 把creatAt設定上去
oneStudent.setCreateDate(ori.getCreateDate());
// 儲存回資料庫
StudentBean savedStudent = studentBeanRepository.save(oneStudent);	
```

---

* 加入Font Awesome 圖案css連結
    * icon網址
        * https://fontawesome.com/v5/search
    * index.html
```
 <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/css/all.css">
```


---
student.component.ts
`npm i @ng-bootstrap/ng-bootstrap --legacy-peer-deps`

```typescript
// 學生修改程式----------------------------------------------------------------------------
  // 變數
  subscriptionCode: any;

  openModalCode(cdocCode?:any) {
    const refCode = this.modal.open(FormStudentCodeComponent, // 將cdoc導入至form.component.ts
      {
        size: 'lg'
      });
      refCode.componentInstance.cdocCode = cdocCode; // 需加入此行，跳出來的Modal才能帶出原始資料
      console.log("studentCode : ", cdocCode.studentCode);

      this.subscriptionCode = refCode.componentInstance.result.subscribe( // 此處result不可改名
        (result:any) => {
          console.log("修改後的程式碼 : ", result);

          const URLGetOne = 'http://localhost:8080/api/student/' + cdocCode.studentId;
          console.log("欲修改的網址 : ",URLGetOne);
          this.http.get<Student>(URLGetOne).subscribe(
            (data) => {
              // 學生
              data.studentId = cdocCode.studentId;
              data.studentCode = result.studentCode;

              const URLPost = 'http://localhost:8080/api/student';
              this.http.post(URLPost, data).subscribe(
                (data2) => {
                  this.onGetAllStudent();
                  console.log('修改成功, 結果是:', data2);
                });
            },
            (error) => {
              console.error('GetAll failed');
              console.error(error);
            });
        }
      )
  }

  editStudentCode (cdocCode:any) {
    this.openModalCode(cdocCode);
  }
```

* form.component.html
```html
<!--設定彈出的視窗有哪些欄位-->
<div class="modal-header">
    <!--表頭-->
    <h4 class="modal-title">修改一位學生</h4>
</div>
<!-- body -->
<div class="modal-body">
    <form #cform="ngForm">
        <!--幫表單取名字，此處為cform-->
        <!--1個form-group，1個欄位-->
        <div class="form-group">
            <div class="row">
                <label for="studentName" class="col-2 col-form-label">學生名稱<span class="text-danger">*</span></label>
                <input type="text" class="col-10 form-control" [(ngModel)]="oneStudentForm.studentName" name="studentName" #studentName="ngModel" placeholder="學生名稱" required>
                <!--required為html語法，代表必填欄位-->
            </div>
            <div *ngIf="studentName.dirty">
                <!-- if 的判斷 -->
                <!-- 有打過字 → dirty -->
                <span *ngIf="studentName.errors; then errors"></span>
                <!--then errorC的errors可以自填-->
            </div>
        </div>
        <!--1個form-group，1個欄位-->
        <div class="form-group">
            <div class="row">
                <label for="studentScore" class="col-2 col-form-label">學生分數<span class="text-danger">*</span></label>
                <input type="number" class="col-10 form-control" [(ngModel)]="oneStudentForm.studentScore" name="studentScore" #studentScore="ngModel" placeholder="學生分數" required min="0" max="100">
                <!--required為html語法，代表必填欄位-->
            </div>
            <div *ngIf="studentScore.dirty">
                <!-- if 的判斷 -->
                <!-- 有打過字 → dirty -->
                <span *ngIf="studentScore.errors; then errors"></span>
                <!--then errorC的errors可以自填-->
            </div>
        </div>
        <!-- 下拉式選單 -->
        <div class="form-group">
            <div class="row">
                <label for="gradeId">年級ID</label>
                <!-- 可以寫2個[(ngModel)]?? -->
                <select [(ngModel)]="selectedOption" (ngModelChange)="onSelectedOptionChange()" class="form-control" name="gradeId" id="gradeId" #gradeId="ngModel" [(ngModel)]="oneStudentForm.gradeBean.gradeId" name="gradeId">
                    <option *ngFor="let grade of gradeArray" [value]="grade.gradeId">
                        {{ grade.gradeId }}
                    </option>
                </select>
            </div>
        </div>
        <div class="form-group">
            <div>
                <label for="gradeName">年級名稱</label>
                <input type="text" class="col-10 form-control" [(ngModel)]="oneStudentForm.gradeBean.gradeName" name="gradeName" #gradeName="ngModel" placeholder="年級名稱" [value]="selectedGrade.gradeName" required>
            </div>
        </div>
        <div class="form-group">
            <div>
                <label for="gradeHowMany">年級人數</label>
                <!-- <input type="number" name="gradeHowMany" id="gradeHowMany" name="gradeHowMany" ngModel
                        #gradeHowMany="ngModel" class="col-10 form-control" [value]="selectedGrade.gradeHowMany"
                        [(ngModel)]="oneStudentForm.gradeBean.gradeHowMany"
                        /> -->
                <input type="number" class="col-10 form-control" [(ngModel)]="oneStudentForm.gradeBean.gradeHowMany" name="gradeHowMany" #gradeHowMany="ngModel" placeholder="年級人數" [value]="selectedGrade.gradeHowMany" required>
            </div>
        </div>


        <!-- footer區域 -->
        <div class="modal-footer">
            <!--儲存按鈕-->
            <button type="submit" class="btn btn-outline-primary" (click)="save()" [disabled]="!cform.form.valid">儲存</button>
            <!-- !cform.form.valid → 有任何不符合的，都讓按鈕處於[disabled] (無法按下) -->
            <!-- cform.form → 表單屬性-->
        </div>
    </form>
</div>

<!--欄位的錯誤控制-->
<ng-template #errors>
    <!--當出現#errors，都顯示欄位未填！-->
    <p class="text-danger">欄位未填！</p>
</ng-template>
<ng-template #phone_errors>
    <p class="text-danger">手機號碼需10碼！</p>
</ng-template>
<ng-template #toobig_errors>
    <p class="text-danger">超出規定學分數！</p>
</ng-template>

```

```html
export class FormComponent implements OnInit {
  // 應為student型態。此Input來自student.component.ts
  // 於ngOnInit(): void {} 內使用
  @Input() cdoc?:any; 
  // result為變數名稱。
  @Output() result: EventEmitter<any> = new EventEmitter<any>(); // 將資料傳出去

  constructor(
    private http: HttpClient,
    public activeModal:NgbActiveModal,
  ) { }

  ngOnInit(): void {
    this.select();
    // 讀出原始資料
    if (this.cdoc) {
      this.oneStudentForm = {
        studentName:this.cdoc.studentName,
        studentScore:this.cdoc.studentScore,
        gradeBean:this.cdoc.gradeBean,
      }  
    }
  }



  // Modal--------------------------------------------------------------------------
  contactSave() {
    this.activeModal.close("Y");
  }

  save() {
    // oneStudentForm為雙向連結，改html就會改ts，此處設定為關閉表單(即修改完成)後，傳送
    this.result.emit(this.oneStudentForm); // 發出通知，讓subscrib收到 // 把資料丟出去，並未存進資料庫
    this.activeModal.close('儲存');  // 關閉視窗,回傳訊息'儲存'
    // this.activeModal.dismiss()
  }
}

```