iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 28
0
自我挑戰組

Angular 學習雜記系列 第 28

Angular 學習雜記-Angular整合應用網站-員工資料管理系統(十六)

在新增資料時,想到的,就是增加一個新的component,來當新增的畫面,請參考之前的章節,新增一個,名稱為「employee-add」的component。

接下來,在employeeservice.service中,增加addEmployeeinfo的函式來新增員工資料,主要是用輸入的參數,將Employeeinfo物件輸入到函式中,再透過http.post,來新增整個Employeeinfo,程式碼如下:

  // 新增員工資料
  addEmployeeinfo(employeeinfo: Employeeinfo): Observable<Employeeinfo> {
    return this.http.post<Employeeinfo>(this.employeeUrl, employeeinfo, httpOptions)
      .pipe(
        catchError(this.handleError<Employeeinfo>(`addEmployeeinfo`))
    );
  }

在處理好Service後,接下來,在新增加的員工資料新增,可以參考之前,寫的程式,來import 資料類別、Service,增加一個叫addinfo的函式,來處理新增員工資料。employee-add.component.ts的程式碼如下:

import { Component, OnInit } from '@angular/core';
// 引用資料類
import { Employeeinfo } from './../employeeinfo';
// 載入Service
import { EmployeeserviceService } from './../employeeservice.service';
import { ActivatedRoute } from '@angular/router';

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

  employee: Employeeinfo;

  // 建構子
  constructor(
    private employeeService: EmployeeserviceService,
    private route: ActivatedRoute
  ) { }

  // 初始化
  ngOnInit() {
  }

  // 新增員工資料
  addinfo(): void {
    this.employeeService.addEmployeeinfo(this.employee)
      .subscribe();
  }
}

最後,在新的component的網頁設計,可以參考員工明細的畫面,增加輸入的欄位。employee-add.component.html的程式碼如下:

<div>
  <h2>員工新增</h2>
  <div>
    <label>員工編號:
      <input [(ngModel)]="employee.serialnumber" placeholder="serialnumber"/>
    </label>
  </div>
  <div>
    <label>姓名:
      <input [(ngModel)]="employee.name" placeholder="name"/>
    </label>
  </div>
  <div>
    <label>地址:
      <input [(ngModel)]="employee.address" placeholder="address"/>
    </label>
  </div>
  <div>
    <label>銷售額:
      <input [(ngModel)]="employee.sales" placeholder="sales"/>
    </label>
  </div>
  <button (click)="addinfo()">新增</button>
</div>

完成上述程式碼,就可以新增資料。不過,還要設計路由的路徑,大家可以試試加上新的連結及路由。如何解法,靜待下回分解。


上一篇
Angular 學習雜記-Angular整合應用網站-員工資料管理系統(十五)
下一篇
Angular 學習雜記-Angular整合應用網站-員工資料管理系統(十七)
系列文
Angular 學習雜記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言