在以前利用JavaScript 進行HTTP request 時, 通常都會等待一段時間才收到response, 若在multi-thread 的環境下, 有機會傳回null 而令執行上出現問題. 從前須要加入setTimeout() 去等待, 現在在ES5後, 則須加入async await 便可. 在示範中會利用service 執行async HTTP request.
service.ts
import { Injectable, Testability } from '@angular/core'; import { HttpClient, HttpParams, HttpHeaders } from '@angular/common/http'; import { Staff } from './roi-staff'; import { Order } from './roi-order'; import { environment } from '../../environments/environment'; import * as moment from 'moment'; @Injectable({ providedIn: 'root' }) export class RoiService { async findOrdersByDateRangeAndStaffID(startDate: Date, endDate: Date, staffID: number): Promise<Array> { let orders: Array = new Array(); const parameters: HttpParams = new HttpParams({ fromString: this.generateRequestParameters(startDate, endDate, staffID) }); const request = await this.http.get<Array>(environment.servicePath.roiService.findOrdersByApplicationDateAndStaffID, { params: parameters }).toPromise().then( response => { console.debug('Respone collected. no. of record(s) found=' + response.length); orders = response; }, error => { console.error(error); }); return orders; } private generateRequestParameters(startDate: Date, endDate: Date, staffID: number): string { let fromString = ''; if ((startDate != null) && (endDate != null)) { fromString += 'startDate=' + moment(startDate).format('YYYY-MM-DD') + '&endDate=' + moment(endDate).format('YYYY-MM-DD'); } fromString += '&staffID=' + staffID.toString(); return fromString; } }
在service 的export function 中, 加入了async 去界定這是async function, 而Promise<> 則是會傳回的類別. 當執行HTTP request 後會利用toPromise() 確定接回result 後才透過then() 繼續執行. 而它亦可以類似JQuery 的形式, 透過annoymous function 去處理success 及failure response.
而在component 中, 叫用方法如下.
import { Component, OnInit, AfterViewInit } from '@angular/core'; import { AppSettings } from '../../app.settings'; import { Staff } from '../roi-staff'; import { Order } from '../roi-order'; import { RoiService } from '../roi.service'; import { GridDataResult, PageChangeEvent } from '@progress/kendo-angular-grid'; import { SortDescriptor, orderBy } from '@progress/kendo-data-query'; @Component({ selector: 'app-roi-regular-report', templateUrl: './roi-regular-report.component.html', styleUrls: ['./roi-regular-report.component.scss'], providers: [RoiService] }) export class RoiRegularReportComponent implements AfterViewInit { public selectedDepartmentHead: Staff; public orders: Array<Order>; public startDate: Date; public endDate: Date; constructor(private roiService: RoiService) { } async searchCommand() { console.debug('searchCommand() started.'); this.orders = await this.roiService.findOrdersByDateRangeAndStaffID(this.startDate, this.endDate, this.selectedDepartmentHead.staffID); this.loadItems(); } }
叫用的function 亦只須要在function 中加入async 和叫用的code 加入await 便可.
Leave a Reply