typescript 52 lines · 8 steps

Tracking upload progress in Angular

An Angular service streams file-upload progress by folding HttpClient events into a running state object.

Explained by highlit
1import { Injectable } from '@angular/core';
2import { HttpClient, HttpEventType, HttpRequest } from '@angular/common/http';
3import { Observable } from 'rxjs';
4import { map, distinctUntilChanged, scan } from 'rxjs/operators';
5 
6export interface UploadProgress {
7 progress: number;
8 state: 'pending' | 'uploading' | 'done';
9 response?: unknown;
10}
11 
12@Injectable({ providedIn: 'root' })
13export class FileUploadService {
14 constructor(private http: HttpClient) {}
15 
16 upload(file: File): Observable<UploadProgress> {
17 const formData = new FormData();
18 formData.append('file', file, file.name);
19 
20 const request = new HttpRequest('POST', '/api/documents', formData, {
21 reportProgress: true,
22 });
23 
24 return this.http.request(request).pipe(
25 scan<any, UploadProgress>(
26 (state, event) => {
27 switch (event.type) {
28 case HttpEventType.Sent:
29 return { ...state, state: 'uploading' };
30 case HttpEventType.UploadProgress:
31 return {
32 ...state,
33 state: 'uploading',
34 progress: event.total
35 ? Math.round((100 * event.loaded) / event.total)
36 : state.progress,
37 };
38 case HttpEventType.Response:
39 return { state: 'done', progress: 100, response: event.body };
40 default:
41 return state;
42 }
43 },
44 { state: 'pending', progress: 0 },
45 ),
46 distinctUntilChanged(
47 (a, b) => a.progress === b.progress && a.state === b.state,
48 ),
49 map((state) => state),
50 );
51 }
52}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1A reporting HttpRequest emits a stream of typed events rather than a single response, letting you observe progress mid-flight.
  2. 2scan folds a stream into an evolving state object, turning raw events into meaningful UI-ready snapshots.
  3. 3distinctUntilChanged suppresses redundant emissions so subscribers only react when something visible actually changes.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Tracking upload progress in Angular — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code