在明細的部份,也是修改成由記憶體Web API(In-memory Web API)來取得資料,並且,加入處理Error的部份。
原來的程式碼:
  // 依id,取得所屬的員工資料
  getEmployeeinfo(id: number): Observable<Employeeinfo> {
    return of(employeelist.find(employeeinfo => employeeinfo.id === id));
  }
主要的修改是由原來是直接取得假資料的類別,改成透過http.get的方式來取得符合id值的單一Employeeinfo的陣列資料。再加入之前的handleError()的函式,就會報告這個錯誤,並且返回一個無害的回傳值。才能正確工作。程式碼如下:
  // 依id,取得所屬的員工資料
  getEmployeeinfo(id: number): Observable<Employeeinfo> {
    // return of(employeelist.find(employeeinfo => employeeinfo.id === id));
    const url = `${this.employeeUrl}/${id}`;
    return this.http.get<Employeeinfo>(url)
      .pipe(
        catchError(this.handleError<Employeeinfo>(`getEmployeeinfo id=${id}`))
    );
  }
這樣,在列表及顯示明細的部份,就完成了。下述程式碼為完整的employeeservice.service.ts程式碼。可以給大家參考。
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { catchError, map, tap} from 'rxjs/operators';
// 引用資料類別
import { Employeeinfo } from './employeeinfo';
const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
@Injectable({
  providedIn: 'root'
})
export class EmployeeserviceService {
  private employeeUrl = 'api/employeeinfos';
  constructor(
    private http: HttpClient) { }
  // 回傳員工資料
  getEmployee(): Observable<Employeeinfo[]> {
    // return of(employeelist);
    return this.http.get<Employeeinfo[]>(this.employeeUrl)
      .pipe(
        catchError(this.handleError<Employeeinfo[]>('getEmployee', []))
      );
  }
  // 依id,取得所屬的員工資料
  getEmployeeinfo(id: number): Observable<Employeeinfo> {
    // return of(employeelist.find(employeeinfo => employeeinfo.id === id));
    const url = `${this.employeeUrl}/${id}`;
    return this.http.get<Employeeinfo>(url)
      .pipe(
        catchError(this.handleError<Employeeinfo>(`getEmployeeinfo id=${id}`))
    );
  }
  private handleError<T>(operation = 'opertion', result?: T) {
    return (error: any): Observable<T> => {
      console.error(error);
      return of(result as T);
    };
  }
}
後續,要開始來處理修改、新增、刪除資料等功能。不過,再之前,要來說明一下什麼是http的CURD。