In some cases your application might need to upload large amounts of data, such as files. Obviously for a good UX we should provide the user some feedback on the progress of the upload. Angular ' s HttpRequest
object has a property reportProgress
which allows us to do exactly. Let's see how.
//Service:Import {injectable} from ' @angular/core '; import {Observable} from' Rxjs/observable 'Import {HttpClient, HttpRequest, httpevent} from' @angular/common/http '; Export interface person {name:string;} @Injectable () Export class Peopleservice {constructor (private http:httpclient) {} uploadavatar (data): Observable<httpevent<Object>>{Const REQ=New HttpRequest(' POST ', ' HTTPS://REQRES.IN/API/USERS/1 ', data, {reportprogress: true } ); return This . http.requesT(req); }}
//ComponentImport {HttpClient, HttpRequest, Httpevent, httpeventtype} from ' @angular/common/http '; Uploadavatar (fileUpload) {const FormData=NewFormData (); Formdata.append (' Avatar ', fileupload.files[0], ' avatar.jpg '); This. Peopleservice. Uploadavatar (formData). Subscribe (Res= { if(Res.type = = = httpeventtype.uploadprogress) {const percentage= Math.Round (* res.loaded/res.total); This. Output = ' File is ${percentage}%uploaded '; } Else if(Resinstanceof HttpResponse) { This. Output =' File is completely uploaded '; } }); }
[Angular] Provide Feedback to Progress Events with Angular ' s HttpRequest Object