Sub topic 13
Tracking Upload and Download Progress
This chapter assumes you have read the earlier chapters on mutation requests and on the observe and responseType options. It also assumes you can use RxJS map and filter inside pipe. By default, HttpClient emits a single value: the response body. That is all most requests need. A large file upload or download takes longer, and users expect a progress bar. To show one, you ask HttpClient for the full stream of HTTP events instead of only the final body.
The two options that turn on progress
You need two request options together:
reportProgress: truetells Angular to emit progress events while bytes are being sent or received.observe: 'events'changes the return type toObservable<HttpEvent<T>>, so you receive every event and not just the body.
If you set reportProgress without observe: 'events', you still get only the body, and the progress events are discarded. This is the most common reason a progress bar never moves.
The event sequence
Each emitted value has a type property that holds a member of the HttpEventType enum.
| Event type | When it fires | Useful fields |
|---|---|---|
| `Sent` | The request has been dispatched | none |
| `UploadProgress` | While the request body is uploading | `loaded`, `total` |
| `ResponseHeader` | Status and headers have arrived | `status`, `headers` |
| `DownloadProgress` | While the response body is downloading | `loaded`, `total` |
| `Response` | The full response is complete | `body`, `status`, `headers` |
An upload service that reports a percentage
The service below maps raw events to a small state object that a template can render. Events the UI does not need are filtered out.
// upload.service.ts
import { Injectable, inject } from '@angular/core';
import { HttpClient, HttpEvent, HttpEventType } from '@angular/common/http';
import { Observable, filter, map } from 'rxjs';
export interface UploadState {
progress: number;
done: boolean;
}
function toUploadState(event: HttpEvent<unknown>): UploadState | null {
switch (event.type) {
case HttpEventType.UploadProgress:
return {
progress: event.total ? Math.round((100 * event.loaded) / event.total) : 0,
done: false
};
case HttpEventType.Response:
return { progress: 100, done: true };
default:
return null;
}
}
@Injectable({ providedIn: 'root' })
export class UploadService {
private readonly http = inject(HttpClient);
upload(file: File): Observable<UploadState> {
const formData = new FormData();
formData.append('file', file);
return this.http
.post('/api/uploads', formData, { reportProgress: true, observe: 'events' })
.pipe(
map(toUploadState),
filter((state): state is UploadState => state !== null)
);
}
}The switch on event.type narrows the union type. That is why TypeScript lets you read event.loaded only inside the UploadProgress branch.
Showing the progress bar
// file-upload.component.ts
import { Component, inject, signal } from '@angular/core';
import { UploadService, UploadState } from './upload.service';
@Component({
selector: 'app-file-upload',
template: `
<input type="file" (change)="onFileSelected($event)" />
@if (state(); as s) {
<progress max="100" [value]="s.progress"></progress>
@if (s.done) {
<p>Upload complete.</p>
}
}
`
})
export class FileUploadComponent {
private readonly uploadService = inject(UploadService);
readonly state = signal<UploadState | null>(null);
onFileSelected(event: Event): void {
const file = (event.target as HTMLInputElement).files?.[0];
if (!file) {
return;
}
this.uploadService.upload(file).subscribe(s => this.state.set(s));
}
}Common errors
totalis undefined.totalis undefined when the size is unknown. For downloads, this happens when the server sends noContent-Lengthheader, for example with chunked or compressed responses. Guard the division, or show an indeterminate spinner in that case.- Too many change detection cycles. Progress events can fire many times per second. Map them to a small state object as shown above, and avoid heavy work in the subscriber.
- Progress stays at zero in development. Local servers often answer instantly. Use the browser's network throttling to see intermediate events.
Exercise
Write a service method download(url: string) that fetches a file as a Blob and emits a progress percentage during the download, then the Blob when the download finishes. Which options and event types do you need?
Show answer
Use this.http.get(url, { responseType: 'blob', reportProgress: true, observe: 'events' }). In a map, return { progress: Math.round(100 * event.loaded / event.total) } when event.type === HttpEventType.DownloadProgress and event.total is defined. Return { progress: 100, file: event.body } when event.type === HttpEventType.Response. Filter out all other event types. The server must send Content-Length for total to be available.
Exercise
A developer passes { reportProgress: true } to http.post but the subscriber receives only one value. Why, and how is it fixed?
Show answer
Without observe: 'events', HttpClient emits only the response body, so the progress events are dropped. Add observe: 'events' and handle HttpEvent values by checking event.type.