Previously, the below code worked fine in Angular for me. However, I am now encountering an error in Angular 14 stating Object is possibly undefined
:
this.progress = Math.round(100 * event.loaded / event.total);
The issue seems to be with the event.total
section. Here is my complete TypeScript code:
import { HttpClient, HttpEventType, HttpErrorResponse } from '@angular/common/http';
import { Component, EventEmitter, OnInit, Output } from '@angular/core';
@Component({
selector: 'app-upload',
templateUrl: './upload.component.html',
styleUrls: ['./upload.component.css']
})
export class UploadComponent implements OnInit {
progress: number;
message: string;
@Output() public onUploadFinished = new EventEmitter();
constructor(private http: HttpClient) { }
ngOnInit() {
}
uploadFile = (files) => {
if (files.length === 0) {
return;
}
let fileToUpload = <File>files[0];
const formData = new FormData();
formData.append('file', fileToUpload, fileToUpload.name);
this.http.post('https://localhost:5001/api/upload', formData, {reportProgress: true, observe: 'events'})
.subscribe({
next: (event) => {
if (event.type === HttpEventType.UploadProgress)
this.progress = Math.round(100 * event.loaded / event.total);
else if (event.type === HttpEventType.Response) {
this.message = 'Upload success.';
this.onUploadFinished.emit(event.body);
}
},
error: (err: HttpErrorResponse) => console.log(err)
});
}
}
Any help on how to resolve this error would be greatly appreciated. Thank you.