Angular9 跟蹤和顯示請求進(jìn)度

2020-07-06 15:31 更新

應(yīng)用程序有時(shí)會(huì)傳輸大量數(shù)據(jù),而這些傳輸可能要花很長時(shí)間。文件上傳就是典型的例子。你可以通過提供有關(guān)此類傳輸?shù)倪M(jìn)度反饋,為用戶提供更好的體驗(yàn)。

要想發(fā)出一個(gè)帶有進(jìn)度事件的請求,你可以創(chuàng)建一個(gè) HttpRequest 實(shí)例,并把 reportProgress 選項(xiàng)設(shè)置為 true 來啟用對進(jìn)度事件的跟蹤。

Path:"app/uploader/uploader.service.ts (upload request)" 。

const req = new HttpRequest('POST', '/upload/file', file, {
  reportProgress: true
});

注:

  • 每個(gè)進(jìn)度事件都會(huì)觸發(fā)變更檢測,所以只有當(dāng)需要在 UI 上報(bào)告進(jìn)度時(shí),你才應(yīng)該開啟它們。

  • 當(dāng) HttpClient.request()HTTP 方法一起使用時(shí),可以用 observe: 'events' 來查看所有事件,包括傳輸?shù)倪M(jìn)度。

接下來,把這個(gè)請求對象傳遞給 HttpClient.request() 方法,該方法返回一個(gè) HttpEventsObservable(與 攔截器 部分處理過的事件相同)。

Path:"app/uploader/uploader.service.ts (upload body)" 。

// The `HttpClient.request` API produces a raw event stream
// which includes start (sent), progress, and response events.
return this.http.request(req).pipe(
  map(event => this.getEventMessage(event, file)),
  tap(message => this.showProgress(message)),
  last(), // return last (completed) message to caller
  catchError(this.handleError(file))
);

getEventMessage 方法解釋了事件流中每種類型的 HttpEvent。

Path:"app/uploader/uploader.service.ts (getEventMessage)" 。

/** Return distinct message for sent, upload progress, & response events */
private getEventMessage(event: HttpEvent<any>, file: File) {
  switch (event.type) {
    case HttpEventType.Sent:
      return `Uploading file "${file.name}" of size ${file.size}.`;


    case HttpEventType.UploadProgress:
      // Compute and show the % done:
      const percentDone = Math.round(100 * event.loaded / event.total);
      return `File "${file.name}" is ${percentDone}% uploaded.`;


    case HttpEventType.Response:
      return `File "${file.name}" was completely uploaded!`;


    default:
      return `File "${file.name}" surprising upload event: ${event.type}.`;
  }
}

本指南中的示例應(yīng)用中沒有用來接受上傳文件的服務(wù)器。"app/http-interceptors/upload-interceptor.ts" 的 UploadInterceptor 通過返回一個(gè)模擬這些事件的可觀察對象來攔截和短路上傳請求。

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)