Progress Events
Progress events are useful for tracking the progress of HTTP requests in Angular. This guide covers the basics of implementing progress event handling using Angular's HTTP Client.
Setting Up HTTPClientModule
First, import the HttpClientModule
into your app module:
// app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
import { DataService } from './data.service';
import { HomeComponent } from './home/home.component';
@NgModule({
declarations: [AppComponent, HomeComponent],
imports: [BrowserModule, HttpClientModule],
providers: [DataService],
bootstrap: [AppComponent]
})
export class AppModule { }
Creating a Service
Next, create a service to manage HTTP requests using the Angular CLI command:
$ ng generate service data
This command generates a new service file named data.service.ts
.
Implementing Progress Event Handling
In the service file, inject the HttpClient
and create a method to perform HTTP requests with progress event tracking:
// data.service.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpEvent, HttpEventType, HttpHeaders, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class DataService {
private apiUrl = 'https://jsonplaceholder.typicode.com/posts';
constructor(private http: HttpClient) { }
uploadFile(file: File): Observable {
const formData = new FormData();
formData.append('file', file);
const req = new HttpRequest('POST', this.apiUrl, formData, {
reportProgress: true,
headers: new HttpHeaders({ 'enctype': 'multipart/form-data' })
});
return this.http.request(req).pipe(
map(event => this.getEventMessage(event, file))
);
}
private getEventMessage(event: HttpEvent, file: File): number {
switch (event.type) {
case HttpEventType.UploadProgress:
return Math.round(100 * (event.loaded / (event.total || 1)));
case HttpEventType.Response:
return 100;
default:
return 0;
}
}
}
Using the Service in a Component
Inject the service into your component's constructor and use it to upload files and track progress:
// home.component.ts
import { Component } from '@angular/core';
import { DataService } from '../data.service';
@Component({
selector: 'app-home',
template: `
File Upload
= 0">Progress: {{ progress }}%
`
})
export class HomeComponent {
progress = -1;
constructor(private dataService: DataService) {}
onFileSelected(event: any) {
const file: File = event.target.files[0];
if (file) {
this.dataService.uploadFile(file).subscribe(progress => {
this.progress = progress;
});
}
}
}
Handling Errors
To handle errors in your HTTP requests with progress events, use the catchError
operator from RxJS:
// data.service.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpEvent, HttpEventType, HttpHeaders, HttpRequest, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class DataService {
private apiUrl = 'https://jsonplaceholder.typicode.com/posts';
constructor(private http: HttpClient) { }
uploadFile(file: File): Observable {
const formData = new FormData();
formData.append('file', file);
const req = new HttpRequest('POST', this.apiUrl, formData, {
reportProgress: true,
headers: new HttpHeaders({ 'enctype': 'multipart/form-data' })
});
return this.http.request(req).pipe(
map(event => this.getEventMessage(event, file)),
catchError(this.handleError)
);
}
private getEventMessage(event: HttpEvent, file: File): number {
switch (event.type) {
case HttpEventType.UploadProgress:
return Math.round(100 * (event.loaded / (event.total || 1)));
case HttpEventType.Response:
return 100;
default:
return 0;
}
}
private handleError(error: HttpErrorResponse) {
console.error('Server Error:', error);
return throwError('Something went wrong with the request.');
}
}
Key Points
- Progress events are useful for tracking the progress of HTTP requests in Angular.
- Import
HttpClientModule
in your app module to set up the HTTP Client. - Create a ser