Angular9 跟蹤和顯示請求進度

2020-07-06 15:31 更新

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

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

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

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

注:

  • 每個進度事件都會觸發(fā)變更檢測,所以只有當需要在 UI 上報告進度時,你才應該開啟它們。

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

接下來,把這個請求對象傳遞給 HttpClient.request() 方法,該方法返回一個 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}.`;
  }
}

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

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

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號