I have successfully implemented a solution in Angular 13 / RxJs 7 for tracking download progress.
To start, I created some enums:
export enum RequestType {
get = 'GET',
post = 'POST',
put = 'PUT',
delete = 'DELETE',
}
export enum ActionType {
download = 1,
upload
}
Next, I developed a shared service to manage progress tracking:
@Injectable({
providedIn: 'root'
})
export class DownloadProgressService {
percentDone = 0;
actionType: ActionType;
constructor(private http: HttpClient) { }
downloadFile(uri: string, requestType: RequestType, actionType: ActionType, body: any): Observable<number> {
this.actionType = actionType;
const req = new HttpRequest(requestType, uri, body, {
reportProgress: true,
responseType: 'blob'
});
return this.http
.request(req)
.pipe(
map(event => this.getPercentage(event)),
);
}
public getPercentage(event: HttpEvent<any>): number {
switch (event.type) {
case HttpEventType.UploadProgress:
// Ignore upload progress for download actions
if (this.actionType !== ActionType.upload) {
return 0;
}
// Calculate and display % completion:
if (event && event.total) {
this.percentDone = Math.round(100 * event.loaded / event.total);
return this.percentDone;
} else {
return 0;
}
case HttpEventType.DownloadProgress:
if (event && event.total) {
this.percentDone = Math.round(100 * event.loaded / event.total);
}
return this.percentDone;
default:
// Irrelevant event type
return this.percentDone;
}
}
}
Then, I subscribed to the service to monitor the download progress:
this.downloadService
.downloadFile(url, RequestType.post, ActionType.download, body)
.subscribe(progress => this.progress = progress);
Everything is functioning well, and I can view real-time progress in the component library's progress bar.
Now, my question is ... how do I access the downloaded file?