在連結明細之前,我們發現一個問題,那就是在建立Service時,雖然,目前,可以顯示出資料,但因為目前用的是假資料,不會有非同步的問題,但是,如果後續要用到正式的web api的資料時,就必須要處理非同步的問題,所以,在Angular,有非同步的處理機制,由Service的Observable(可觀察)物件及Client的subscribe(訂閱)物件,來組成非同步處理的機制。
所以,要先將之前的程式,修正為此機制,才能學習到Service的正確處理方式。
在employeeservice.service.ts的程式碼中,先import有關Angular的處理物件rxjs。再修改getEmployee函式中,在回傳時,增加Observable物件,及回傳employeelist時,用of物件回傳。程式碼如下:
import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
// 引用資料類別
import { Employeeinfo } from './employeeinfo';
// 引用資料
import { employeelist } from './employeelist';
@Injectable({
  providedIn: 'root'
})
export class EmployeeserviceService {
  constructor() { }
  // 回傳員工資料
  getEmployee(): Observable<Employeeinfo[]> {
    return of(employeelist);
  }
}
在employee-list.component.ts中,修改getEmployees()函式,增加subscribe的方式,來取得回傳的employee物件。程式碼如下:
  getEmployees(): void {
    // 處理非同步機制。
    this.employeeService.getEmployee()
      .subscribe(employeelists => this.employeelists = employeelists);
  }
在employee-sales-list.component.ts中,修改getEmployees()函式,增加subscribe的方式,來取得回傳的employee物件,並且處理資料排序及取得前二名員工。程式碼如下
getEmployees(): void {
    // 先排序,再取前二名員工資料
    // 處理非同步機制。
    this.employeeService.getEmployee()
      .subscribe(employesaleslists => {
        // tslint:disable-next-line: only-arrow-functions
        this.employesaleslists = employesaleslists.sort(function(a, b) {
          return b.sales - a.sales;
        }).splice(0, 2);
      });
  }
處理好非同步的問題後,就可以正式顯示明細資料。
 
這個 employesaleslists 是不是要改成 employeelists
在(三)的時候宣告的是 employeelists: Employeeinfo[] = [];
這邊沒有另外宣告 employesaleslists