Sometimes applications transfer large amounts of data and those transfers can take a long time. File uploads are a typical example. You can give the users a better experience by providing feedback on the progress of such transfers.
To make a request with progress events enabled, create an instance of HttpRequest with the reportProgress option set true to enable tracking of progress events.
const req = new HttpRequest('POST', '/upload/file', file, {
reportProgress: true
}); TIP: Every progress event triggers change detection, so only turn them on if you need to report progress in the UI.
When using
HttpClient.request()with an HTTP method, configure the method withobserve: 'events'to see all events, including the progress of transfers.
Next, pass this request object to the HttpClient.request() method, which returns an Observable of HttpEvents (the same events processed by interceptors).
// 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)) );
The getEventMessage method interprets each type of HttpEvent in the event stream.
/** 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 = event.total ? Math.round(100 * event.loaded / event.total) : 0;
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}.`;
}
} The sample app for this guide doesn't have a server that accepts uploaded files. The
UploadInterceptorinapp/http-interceptors/upload-interceptor.tsintercepts and short-circuits upload requests by returning an observable of simulated events.
© 2010–2023 Google, Inc.
Licensed under the Creative Commons Attribution License 4.0.
https://angular.io/guide/http-track-show-request-progress