[Angular] 利用HttpClient 進行async request

在以前利用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 便可.

About C.H. Ling 262 Articles
a .net / Java developer from Hong Kong and currently located in United Kingdom. Thanks for Google because it solve many technical problems so I build this blog as return. Besides coding and trying advance technology, hiking and traveling is other favorite to me, so I will write down something what I see and what I feel during it. Happy reading!!!

Be the first to comment

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.