Cookies concent notice

This site uses cookies from Google to deliver its services and to analyze traffic.
Learn more
Skip to main content
This site is no longer updated.Head to Angular.devHome
/

This is the archived documentation for Angular v17. Please visit angular.dev to see this page for the current version of Angular.

HTTP - Track and show request progress

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.

Make a request

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.

app/uploader/uploader.service.ts (upload request)
      
      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 with observe: 'events' to see all events, including the progress of transfers.

Track request progress

Next, pass this request object to the HttpClient.request() method, which returns an Observable of HttpEvents (the same events processed by interceptors).

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))
);
    

The getEventMessage method interprets each type of HttpEvent in the event stream.

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 = 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 UploadInterceptor in app/http-interceptors/upload-interceptor.ts intercepts and short-circuits upload requests by returning an observable of simulated events.

Last reviewed on Mon Feb 27 2023