W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
應用程序有時會傳輸大量數(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()
方法,該方法返回一個 HttpEvents
的 Observable
(與 攔截器 部分處理過的事件相同)。
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
通過返回一個模擬這些事件的可觀察對象來攔截和短路上傳請求。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: